﻿using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;

//////////////////////////////////////////////////////////////////////////
//Advisee.aspx.cs                                                       //
//Last Edited: 26 Apr 2012                                              //
//                                                                      //
//The page where advisors view and edit advisee schedules.              //
//////////////////////////////////////////////////////////////////////////
public partial class Advisor_SelectAdvisee : System.Web.UI.Page
{
    //////////////////////
    //Instance Variables//
    //////////////////////
    List<Course> courseList = new List<Course>(); //list of courses in schedule
    List<Elective> electiveList = new List<Elective>(); //list of electives in schedule

    //////////////////
    //Page Functions//
    //////////////////

    /// <summary>
    /// Page_Load() 
    /// 
    /// Ininitializes the page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        //If this is the first time we load the page
        if (!IsPostBack)
        {
            //Redirect back to the default page if no advisor ID is detected
            if (Session["Advisor_advisorID"] == null)
                Page.Response.Redirect("Default.aspx");
            //Determine if this advisor is an administrator
            //Get all the advisees this advisor should be able to see and add them to the drop down menu of advisees
            List<Dictionary<String, Object>> results;
            if ((Boolean)Session["isAdmin"])
            {
                results = StoredProcedures.getAllAdvisees();
            }
            else
            {
                results = StoredProcedures.getAdvisees(Session["Advisor_advisorID"].ToString());
            }
            //Clear the AdviseeList to add the Advisee names
            AdviseeList.Items.Clear();
            AdviseeList.Items.Add(new ListItem("Choose Advisee"));
            foreach (Dictionary<String, Object> i in results)
            {
                ListItem advisee = new ListItem(i["lastName"] + ", " + i["firstName"], (String)i["adviseeID"]);
                AdviseeList.Items.Add(advisee);
            }
            String aid = Request.QueryString["id"];
            if (aid != null)
            {
                foreach (ListItem i in AdviseeList.Items)
                {
                    if (i.Value.Equals(aid))
                    {
                        AdviseeList.SelectedIndex = AdviseeList.Items.IndexOf(i);
                        break;
                    }
                }
                //If an advisee is selected
                if (AdviseeList.SelectedIndex != 0)
                {
                    //purge previous advisee's transcript
                    if (Session["Advisor_adviseeIDGV"] != null && !Session["Advisor_adviseeIDGV"].Equals(AdviseeList.SelectedItem.Value))
                    {
                        StoredProcedures.purgeAdviseeTranscript("" + Session["Advisor_adviseeIDGV"], "" + Session["Advisor_advisorID"]);
                    }
                    //Determine the advisee's start date and display it on the page
                    AdviseeName.Text = AdviseeList.SelectedItem.Text;
                    Dictionary<String, Object> result = StoredProcedures.getAdviseeStartTerm(AdviseeList.SelectedItem.Value);
                    String st = result["startTerm"] as String;
                    if(!SharedFunctions.isInitialized(AdviseeList.SelectedItem.Value))
                    {
                        StartDate.Text = "Uninitialized";
                    }
                    else
                    {
                        StartDate.Text = SharedFunctions.convertFromTermCode(result["startTerm"].ToString());
                        if (ViewRadio.SelectedIndex == 0)
                        {
                            initializeJavaScript();
                            //Change State of Elements
                            setEverything(false, false, false, false, true, false, true, false, true, true, false); 
                        }
                        else
                        {
                            //Display the list view
                            generateListViewTable();
                            //Change State of Elements
                            HeaderText.Text = "List View";
                            setEverything(false, false, false, false, false, true, true, false, true, true, false);
                        }
                    }
                }
                else Response.Redirect("~/Advisor/Advisee.aspx");
            }
        }
        else //We had a post back of the page - this is not the first time the page has been loaded
        {
            if (AdviseeList.SelectedIndex == 0 && Session["Advisor_adviseeIDGV"] != null)
            {
                StoredProcedures.purgeAdviseeTranscript("" + Session["Advisor_adviseeIDGV"], "" + Session["Advisor_advisorID"]);
            }
            //If an advisee is selected
            if (AdviseeList.SelectedIndex != 0)
            {
                //if there is a newly selected advisee purge the transcript of the previous advisee
                if (Session["Advisor_adviseeIDGV"] != null && !Session["Advisor_adviseeIDGV"].Equals(AdviseeList.SelectedItem.Value))
                {
                    StoredProcedures.purgeAdviseeTranscript("" + Session["Advisor_adviseeIDGV"], "" + Session["Advisor_advisorID"]);
                }
                //Determine the advisee's start date and display it on the page
                AdviseeName.Text = AdviseeList.SelectedItem.Text;
                Dictionary<String, Object> result = StoredProcedures.getAdviseeStartTerm(AdviseeList.SelectedItem.Value);
                String st = result["startTerm"] as String;
                if (!SharedFunctions.isInitialized(AdviseeList.SelectedItem.Value))
                {
                    StartDate.Text = "Uninitialized";
                }
                else
                {
                    StartDate.Text = SharedFunctions.convertFromTermCode(result["startTerm"].ToString());
                    if (ViewRadio.SelectedIndex == 0)
                    {
                        initializeJavaScript();
                        //Change State of Elements
						setEverything(false, false, false, false, true, false, true, false, true, true, false);
                    }
                    else
                    {
                        //Display the list view
                        generateListViewTable();
                        //Change State of Elements
                        HeaderText.Text = "List View";
						setEverything(false, false, false, false, false, true, true, false, true, true, false);
                    }
                }
            }
        }
    } //end Page_Load()


    
    /// <summary>
    /// ReinitializeAdvisee_Click()
    /// 
    /// Uninitializes the currently selected advisee
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void ReinitializeAdvisee_Click(object sender, EventArgs e)
    {

        if (AdviseeList.SelectedIndex != 0)
        {
            if (StoredProcedures.uninitializeAdvisee(AdviseeList.SelectedValue) == StoredProcedures.FAILURE)
            {
                MessageBox.Show("There was a problem uninitializing this advisee");
            }
            else
            {
                Response.Redirect("~/Advisor/Advisee.aspx");
            }
        }
        else
        {
            return;
        }
    } //ends ReinitializeAdvisee_Click()


    /// <summary>
    /// HomeButton_Click()
    /// 
    /// Redirects to the advisor default page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void HomeButton_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Advisor/Default.aspx");
    } //ends HomeButton_Click()

    /// <summary>
    /// AddCourseChangeDisplayedSemester()
    /// 
    /// Updates all the semester lists on the page to reflect the appropriate semester to display (depending on start date)
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void AddCourseChangeDisplayedSemester(object sender, EventArgs e)
    {
        //Change State of elements
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        HeaderText.Text = "Add A Course To " + AdviseeList.SelectedItem.Text + "'s Schedule";
        CancelButton.Text = "Cancel";
		setEverything(false, true, false, false, false, false, false, true, false, false, false);
        ChangeDisplayedSemesterHelper(YearList, SemesterList);
    } //ends AddCourseChangeDisplayedSemester()

    /// <summary>
    /// CreateElectiveChangeDisplayedSemester()
    /// 
    /// Updates all the semester lists on the page to reflect the appropriate semester to display (depending on start date)
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void CreateElectiveChangeDisplayedSemester(object sender, EventArgs e)
    {
        //Change state of elements
        //Keep in Add Elective view
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        //borderStyle.Text = "<style>.boxBorder {border-bottom:2px solid #000000;}</style>";
        HeaderText.Text = "Add An Elective To Template";
        if (ElectiveSubjectList.SelectedItem != null) ElectiveCourseHeader.Text = ElectiveSubjectList.SelectedItem.Text;
        //setEverything(false, false, false, false, true, false, false, true, false);
        setEverything(false, false, false, false, false, false, false, true, false, false, true);
        ChangeDisplayedSemesterHelper(ElectiveYearList, ElectiveSemesterList);
    } //ends CreateElectiveChangeDisplayedSemester

    /// <summary>
    /// AddElectiveChangeDisplayedSemester()
    /// 
    /// Updates all the semester lists on the page to reflect the appropriate semester to display (depending on start date)
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void AddElectiveChangeDisplayedSemester(object sender, EventArgs e)
    {
        //Change State of elements
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        HeaderText.Text = "Add An Elective To " + AdviseeList.SelectedItem.Text + "'s Schedule";
        CancelButton.Text = "Cancel";
		setEverything(false, false, true, false, false, false, false, true, false, false,false);
        ChangeDisplayedSemesterHelper(ElectiveYearList, ElectiveSemesterList);
    } //ends AddElectiveChangeDisplayedSemester()

    /// <summary>
    /// MoveCourseChangeDisplayedSemester()
    /// 
    /// Updates all the semester lists on the page to reflect the appropriate semester to display (depending on start date)
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void MoveCourseChangeDisplayedSemester(object sender, EventArgs e)
    {
        ChangeDisplayedSemesterHelper(MoveYearList, MoveCourseList);
    } //ends MoveCourseChangeDisplayedSemester()

    /// <summary>
    /// HelpButton_Click()
    /// 
    /// Redirects to the advisor help page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void HelpButton_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Advisor/Help.aspx");
    } //end HelpButton_Click()

    /// <summary>
    /// PrintButton_Click()
    /// 
    /// Called when user clicks the Print button.
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void PrintButton_Click(object sender, EventArgs e)
    {
        //Initialize values for generating PDF
        String uid = AdviseeList.SelectedItem.Value;
        String path = Server.MapPath("~/PDFs") + "/Schedule" + uid + ".pdf";
        List<Course> courses = populateCourses();
        List<Elective> electives = populateElectives();
        //Generate PDF
        SharedFunctions.generatePDF(uid, path, courses, electives, false);
        Dictionary<String, object> name = StoredProcedures.getAdviseeName(uid);
        try
        {
            //Tell browser to download PDF
            WebClient req = new WebClient();
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.Buffer = true;
            Response.AddHeader("Content-Disposition", "attachment;filename=" + name["firstName"] + "_" + name["lastName"] + "_" + uid + "_Schedule" + ".pdf");
            byte[] data = req.DownloadData(path);
            Response.BinaryWrite(data);
            Response.End();
        }
        catch (Exception ex)
        {
            //Do nothing on exception
        }
        finally
        {
            //Remove PDF so it doesn't linger on filesystem
            File.Delete(path);
        }
    } //end PrintButton_Click()

    /// <summary>
    /// SelectAdvisee()
    /// 
    /// Called when the drop down list of advisees is changed
    /// Populates courses in the student's schedule appropriately and displays the
    /// application to the user
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void SelectAdvisee(object sender, EventArgs e)
    {
        //If there is a valid selection in the drop down menu
        if (AdviseeList.SelectedIndex != 0)
        {
            AdviseeName.Text = AdviseeList.SelectedItem.Text;
            //Determine when the advisee's start date is and display it to the user
            Dictionary<String, Object> result = StoredProcedures.getAdviseeStartTerm(AdviseeList.SelectedValue);
            if (result != null)
            {
                StartDate.Text = SharedFunctions.convertFromTermCode("" + result["startTerm"]);
            }
            if(!SharedFunctions.isInitialized(AdviseeList.SelectedValue))
            {
                //Change State of Elements
                colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
                HeaderText.Text = "Intialize Schedule";
				setEverything(true, false, false, false, false, false, false, false, true, true, false);

                //If the advisee is uninitialized, prompt the advisor to initialize the student's schedule with a 
                //template
                List<Dictionary<String, Object>> templates = StoredProcedures.getTemplates();
                TemplateList.Items.Clear();
                TemplateList.Items.Add(new ListItem("Blank Schedule"));
                foreach (Dictionary<String, Object> i in templates)
                {
                    TemplateList.Items.Add(new ListItem(i["name"].ToString(), i["templateID"].ToString()));
                }
                //Add possible start years from today's date minus 10 years
                int startInt = Convert.ToInt32(DateTime.Now.Year);
                UninitYearList.Items.Clear();
                for (int i = -10; i <= 1; i++)
                {
                    UninitYearList.Items.Add("" + (startInt + i));
                }
            }
            else
            {
                //Determine the advisee's start year and add 10 years from that date to the possible years to move
                //to in a schedule
                String startYear = SharedFunctions.getAdviseeStartYear(AdviseeList.SelectedItem.Value);
                Session["Advisor_yearGV"] = startYear.Substring(startYear.IndexOf(' ') + 1);
                Session["Advisor_adviseeIDGV"] = AdviseeList.SelectedItem.Value;
                //Insert advisee's transcript into internal DB
                StoredProcedures.fetchAdviseeTranscript(AdviseeList.SelectedItem.Value, "" + Session["Advisor_advisorID"]);
                MoveYearList.Items.Clear();
                MoveYearList.Items.Add(new System.Web.UI.WebControls.ListItem("Transfer Credits"));
                for (int i = 0; i < 10; i++)
                {
                    MoveYearList.Items.Add("" + (Convert.ToInt32(startYear) + i));
                }
                //Set selected index to be 1 to handle being able to select semesters before start date (will be handled when
                //switch back to 1)
                MoveYearList.SelectedIndex = 1;
                colorStyle.Text = "";
                if (ViewRadio.SelectedIndex == 0)
                {
                    initializeJavaScript();
                    //Change State of Elements
					setEverything(false, false, false, false, true, false, true, false, true, true, false);
                }
                else
                {
                    //Display the list view
                    generateListViewTable();
                    //Change State of Elements
                    HeaderText.Text = "List View"; 
					setEverything(false, false, false, false, false, true, true, false, true, true, false);
                }
            }
        }
    } // end SelectAdvisee()

    /// <summary>
    /// InitializeButton_Click()
    /// 
    /// Handles all the necessary actions once an uninitialized student is initialized with a template
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void InitializeButton_Click(object sender, EventArgs e)
    {
        //If necessary selections are not made, return out of this function and take no action
        if (UninitYearList.SelectedItem == null || UninitSemesterList.SelectedItem == null || TemplateList.SelectedItem == null)
            return;
        
        //Create the termCode from the Advisor's selections
        ///CHANGE termCode = StoredProcedures.getAdviseeStartDate..
        //String termCode = SharedFunctions.convertToTermCode(UninitYearList.SelectedItem.Text, UninitSemesterList.SelectedItem.Text);
        Dictionary<String, Object> results = StoredProcedures.getAdviseeStartTerm(AdviseeList.SelectedValue);
        String termCode = (String)results["startTerm"];
        Session["Advisor_yearGV"] = SharedFunctions.getAdviseeStartYear(AdviseeList.SelectedValue);
        //Find if the advisee starts in the Spring or summer and adjust appropriately
        int semester = Convert.ToInt32(termCode.Substring(5, 1));
        if (semester != 1)
        {
            Session["Advisor_yearGV"] = (Convert.ToInt32(Session["Advisor_yearGV"]) - 1).ToString();
        }
        //Display to the user the advisee's start date
        StartDate.Text = SharedFunctions.convertFromTermCode(termCode);
        if (!TemplateList.SelectedItem.Text.Equals("Blank Schedule"))
        {

            //find the first course in the template. this will be our offset for converting everything to a schedule.
            List<Dictionary<String, Object>> electives = StoredProcedures.getTemplateElectiveInfo(TemplateList.SelectedValue);
            List<Dictionary<String, Object>> courses = StoredProcedures.getTemplateCourseInfo(TemplateList.SelectedValue);
            //combine these to determine the earliest date
            List<Dictionary<String, Object>> coursesAndElectives = new List<Dictionary<String, Object>>();
            foreach (Dictionary<String, Object> i in electives)
            {
                coursesAndElectives.Add(i);
            }
            foreach (Dictionary<String, Object> i in courses)
            {
                coursesAndElectives.Add(i);
            }
            //Set a very large smallestDate to find the true smallestDate
            int smallestDate = 999999;
            foreach (Dictionary<String, Object> i in coursesAndElectives)
            {
                if (smallestDate > Convert.ToInt32(i["term"]))
                {
                    smallestDate = Convert.ToInt32(i["term"]);
                }
            }
            String smallestDateString = "" + smallestDate;
            //Add 0's to the smallestDateString until it is in an appropriate term code format
            while (smallestDateString.Length < 6)
            {
                smallestDateString = "0" + smallestDateString;
            }
            //Get just the year portion of the smallestDateString
            smallestDateString = smallestDateString.Substring(0, 4);
            smallestDate = Convert.ToInt32(smallestDateString);
            //Find the difference in years
            int smallestDateInSchedule = Convert.ToInt32(termCode.Substring(0, 4));
            int difference = (smallestDateInSchedule - smallestDate) * 100;

            //now that we've determined the difference, start putting these in the schedule for the student.
            foreach (Dictionary<String, Object> i in electives)
            {
                //Copy the elective and put it into their schedule
                String newTermCode = i["term"].ToString();
                //modify termcode if the start term is not in the fall
                if (semester == 2)
                {
                    if (Convert.ToInt32(newTermCode.Substring(5, 1)) != 3)
                    {
                        newTermCode = (Convert.ToInt32(newTermCode) + 1).ToString();
                    }
                    else
                    {
                        newTermCode = (Convert.ToInt32(newTermCode) + 98).ToString();
                    }
                }
                else if (semester == 3)
                {
                    if (Convert.ToInt32(newTermCode.Substring(5, 1)) != 1)
                    {
                        newTermCode = (Convert.ToInt32(newTermCode) + 99).ToString();
                    }
                    else
                    {
                        newTermCode = (Convert.ToInt32(newTermCode) + 2).ToString();
                    }
                }
                newTermCode = (Convert.ToInt32(newTermCode) + difference).ToString();
                
                if (StoredProcedures.insertElectiveIntoSchedule(AdviseeList.SelectedValue, i["electiveID"].ToString(), i["selectedCourseID"].ToString(), newTermCode) == StoredProcedures.FAILURE)
                {
                    //error condition
                    MessageBox.Show("Elective Adding Failure");
                }
            }
            foreach (Dictionary<String, Object> i in courses)
            {
                String newTermCode = i["term"].ToString();
                //modify termcode if the start term is not in the fall
                if (semester == 2)
                {
                    if (Convert.ToInt32(newTermCode.Substring(5, 1)) != 3)
                    {
                        newTermCode = (Convert.ToInt32(newTermCode) + 1).ToString();
                    }
                    else
                    {
                        newTermCode = (Convert.ToInt32(newTermCode) + 98).ToString();
                    }
                }
                else if (semester == 3)
                {
                    if (Convert.ToInt32(newTermCode.Substring(5, 1)) != 1)
                    {
                        newTermCode = (Convert.ToInt32(newTermCode) + 99).ToString();
                    }
                    else
                    {
                        newTermCode = (Convert.ToInt32(newTermCode) + 2).ToString();
                    }
                }
                newTermCode = (Convert.ToInt32(newTermCode) + difference).ToString();
                StoredProcedures.insertCourseIntoSchedule(AdviseeList.SelectedValue, i["courseID"].ToString(), newTermCode);
            }
        }
        //Change the move year list to update with appropriate years
        MoveYearList.Items.Clear();
        String startYear = SharedFunctions.getAdviseeStartYear(AdviseeList.SelectedItem.Value);
        Session["Advisor_adviseeIDGV"] = AdviseeList.SelectedItem.Value;
        StoredProcedures.fetchAdviseeTranscript(AdviseeList.SelectedItem.Value, "" + Session["Advisor_advisorID"]);
        MoveYearList.Items.Clear();
        MoveYearList.Items.Add(new System.Web.UI.WebControls.ListItem("Transfer Credits"));
        for (int i = 0; i < 10; i++)
        {
            MoveYearList.Items.Add("" + (Convert.ToInt32(startYear) + i));
        }
        //Set the initial year to be the second one in the list so the first semester check can be done...
        MoveYearList.SelectedIndex = 1;
        ChangeDisplayedSemesterHelper(MoveYearList, MoveCourseList);
        //Change State of Elements
        colorStyle.Text = "";
        if (ViewRadio.SelectedIndex == 0)
        {
            initializeJavaScript();
            //Change State of Elements
			setEverything(false, false, false, false, true, false, true, false, true, true, false);
        }
        else
        {
            //Display the list view
            generateListViewTable();
            //Change State of Elements
            HeaderText.Text = "List View";
			setEverything(false, false, false, false, false, true, true, false, true, true, false);
        }
    } //end InintializeButton_Click()

    /// <summary>
    /// MoveCourseButton_Click()
    /// List View Function
    /// 
    /// Moves a course in List View
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void MoveCourseButton_Click(object sender, EventArgs e)
    {
        //If there's no selected course, just return
        if (ListViewSelectedCourse.Text == "")
            return;
        searchForCourseToModify();
        generateListViewTable();
    } // end MoveCourseButton_Click()

    /// ManageCourseButtonGV_Click()
    /// Graphical View Function
    /// 
    /// Redirects the user to the ManageCourse page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void ManageCourseButtonGV_Click(object sender, EventArgs e)
    {
        //Get the course id stored in the manage button
        Button bb = sender as Button;
        String cid = bb.ID;
        //Get advisee ID
        String adviseeID = (String)Session["Advisor_adviseeIDGV"];
        //If this is a course (third character is a 'c')
        if (cid[2] == 'c')
        {
            //Redirect to Manage Course Page
            Response.Redirect("~/Advisor/ManageCourse.aspx?cid=" + cid.Substring(3) + "&return=a" + adviseeID);
        }
        //If this is an elective (third character is a 'e')
        else if (cid[2] == 'e')
        {
            //Change View to Add Elective and "manage" that way
            cid = cid.Substring(cid.IndexOf("%") + 1);
            SatisfyCourseList.Items.Clear();
            ElectiveListBox.Items.Clear();
            //Change State of elements
            colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
            HeaderText.Text = "Elective Info";
            CancelButton.Text = "Cancel";
            setEverything(false, false, true, false, false, false, false, true, false, false, false);
            Dictionary<String, object> result = StoredProcedures.getElectiveName(cid);
            ElectiveName.Text = (String)result["name"];
            ElectiveManageLabel.Text = cid;
            ElectiveListBox.Items.Add(new ListItem("" + result["name"]));
            List<Dictionary<String, object>> choices = StoredProcedures.getElectiveChoices(cid);
            foreach (Dictionary<String, object> i in choices)
            {
                SatisfyCourseList.Items.Add(new ListItem("" + i["dpt"] + " " + i["num"] + ": " + i["name"] + ", Credits: " + i["credits"], "" + i["courseID"]));
            }
            
            //set all the unusable controls to invisible and disabled, they should be removed w/ all other old stuff
            ElectiveYearList.Visible = false;
            ElectiveYearList.Enabled = false;
            ElectiveSemesterList.Enabled = false;
            ElectiveSemesterList.Visible = false;
            ViewElectiveButton.Enabled = false;
            ViewElectiveButton.Visible = false;
            AddElectiveSemesterList.Visible = false;
            AddElectiveSemesterList.Enabled = false;
            AddElectiveYearList.Enabled = false;
            AddElectiveYearList.Visible = false;
            AddSelectedElectiveButton.Enabled = false;
            AddSelectedElectiveButton.Visible = false;
        }
    } //end ManageCourseButtonGV_Click()

    /// <summary>
    /// RemoveCourseButtonGV_Click()
    /// Graphical View Function
    /// 
    /// Removes a course
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void RemoveCourseButtonGV_Click(object sender, EventArgs e)
    {
        //Get the course id from the Remove button and remove it
        Button bb = sender as Button;
        String cid = bb.ID;
        String adviseeID = (String)Session["Advisor_adviseeIDGV"];
        if (cid[2] == 'c')
        { 
            StoredProcedures.removeCourseFromSchedule(adviseeID, cid.Substring(3));
        }
        else if (cid[2] == 'e')
        {
            String[] electiveAndCourseID = cid.Split('%');
            StoredProcedures.removeElectiveFromSchedule(adviseeID, electiveAndCourseID[2], electiveAndCourseID[1]);
        }
        initializeJavaScript();
    } //end RemoveCourseButtonGV_Click()

    /// ManageCourseButtonLV_Click()
    /// List View Function
    /// 
    /// Redirects the user to the ManageCourse page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void ManageCourseButtonLV_Click(object sender, EventArgs e)
    {
        String cid = ListViewSelectedCourse.Text;
        if (cid[0] == 'c')
        {
            Response.Redirect("ManageCourse.aspx?cid=" + cid.Substring(1));
        }
        else if (cid[0] == 'e')
        {
            cid = cid.Substring(1, cid.IndexOf("%") - 1);
            SatisfyCourseList.Items.Clear();
            ElectiveListBox.Items.Clear();
            //Change State of elements
            colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
            HeaderText.Text = "Elective Info";
            CancelButton.Text = "Cancel";
            setEverything(false, false, true, false, false, false, false, true, false, false, false);
            Dictionary<String, object> result = StoredProcedures.getElectiveName(cid);
            ElectiveName.Text = (String)result["name"];
            ElectiveManageLabel.Text = cid;
            ElectiveListBox.Items.Add(new ListItem("" + result["name"]));
            List<Dictionary<String, object>> choices = StoredProcedures.getElectiveChoices(cid);
            foreach (Dictionary<String, object> i in choices)
            {
                SatisfyCourseList.Items.Add(new ListItem("" + i["dpt"] + " " + i["num"] + ": " + i["name"] + ", Credits: " + i["credits"], "" + i["courseID"]));
            }

            //set all the unusable controls to invisible and disabled, they should be removed w/ all other old stuff
            ElectiveYearList.Visible = false;
            ElectiveYearList.Enabled = false;
            ElectiveSemesterList.Enabled = false;
            ElectiveSemesterList.Visible = false;
            ViewElectiveButton.Enabled = false;
            ViewElectiveButton.Visible = false;
            AddElectiveSemesterList.Visible = false;
            AddElectiveSemesterList.Enabled = false;
            AddElectiveYearList.Enabled = false;
            AddElectiveYearList.Visible = false;
            AddSelectedElectiveButton.Enabled = false;
            AddSelectedElectiveButton.Visible = false;
        }
    } //end ManageCourseButtonLV_Click()

    /// <summary>
    /// RemoveCourseButtonLV_Click()
    /// List View Function
    /// 
    /// Removes a course in List View
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void RemoveCourseButtonLV_Click(object sender, EventArgs e)
    {
        if (ListViewSelectedCourse.Text == "")
            return;
        searchForCourseToRemove();
        generateListViewTable();
    } //end RemoveCourseButtonLV_Click()

    /// <summary>
    /// AddCourse_Click()
    /// 
    /// Displays the appropriate elements when the user hits the add course button
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void AddCourse_Click(object sender, EventArgs e)
    {
        //Populate Subject List
        Dictionary<String, String> courses = SharedFunctions.getDptAcronymToString();
        SubjectList.Items.Clear();
        SubjectList.Items.Add(new ListItem("All Courses"));
        foreach (String s in courses.Keys)
        {
            SubjectList.Items.Add(new ListItem(courses[s], s));
        }
        //Clear Course list
        CourseList.Items.Clear();
        //Populate with 10 years plus the advisee's start date
        String startYear = SharedFunctions.getAdviseeStartYear(AdviseeList.SelectedItem.Value);
        YearList.Items.Clear();
        for (int i = 0; i < 10; i++)
        {
            YearList.Items.Add("" + (Convert.ToInt32(startYear) + i));
        }
        YearList.SelectedIndex = 1;
        //Change State of elements
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        HeaderText.Text = "Add A Course To " + AdviseeList.SelectedItem.Text + "'s Schedule";
        CancelButton.Text = "Cancel";
		setEverything(false, true, false, false, false, false, false, true, false, false, false);
    } // end AddCourse_Click()

    /// <summary>
    /// AddElective_Click()
    /// 
    /// Displays the appropriate elements when the user hits the Add elective button
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void AddElective_Click(object sender, EventArgs e)
    {
        //Populate Subject List
        Dictionary<String, String> courses = SharedFunctions.getDptAcronymToString();
        ElectiveSubjectList.Items.Clear();
        ElectiveSubjectList.Items.Add(new ListItem("All Courses"));
        foreach (String s in courses.Keys)
        {
            ElectiveSubjectList.Items.Add(new ListItem(courses[s], s));
        }
        //Populate the year list with years where the Advisee can add a course/elective (10 years from the student's start date)
        String startYear = SharedFunctions.getAdviseeStartYear(AdviseeList.SelectedItem.Value);
        ElectiveYearList.Items.Clear();
        for (int i = 0; i < 10; i++)
        {
            ElectiveYearList.Items.Add("" + (Convert.ToInt32(startYear) + i));
        }
        ElectiveYearList.SelectedIndex = 1;
        //Change State of elements
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        HeaderText.Text = "Add An Elective To " + AdviseeList.SelectedItem.Text + "'s Schedule";
        CancelButton.Text = "Cancel";
		setEverything(false, false, true, false, false, false, false, true, false, false, false);
    } // end AddElective_Click()

    /// <summary>
    /// CreateElective_Click()
    /// ERIC todo
    /// 
    /// Displays the appropriate elements when the user htis the Create Elective button from the left column menu
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void CreateElective_Click(object sender, EventArgs e)
    {
        //Populate Subject List
        Dictionary<String, String> courses = SharedFunctions.getDptAcronymToString();
        ElectiveSubjectList.Items.Clear();
        ElectiveSubjectList.Items.Add(new ListItem("All Courses"));
        foreach (String s in courses.Keys)
        {
            ElectiveSubjectList.Items.Add(new ListItem(courses[s], s));
        }
        //Change Content
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        HeaderText.Text = "Create An Elective for the Template";
        //Change State of elements
        setAddCourseView(false);
        setAddElectiveView(false);
        setGraphicalView(false);
        setListView(false);
        setPageControls(false, true, false, false);
        setCreateElectiveView(true);

    } // end CreateElective_Click()

    /// <sumary>
    /// ViewElectiveButton_Click()
    /// 
    /// Displays the appropriate elements when the user hits the View button
    /// </sumary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void ViewElectiveButton_Click(object sender, EventArgs e)
    {

        if (ElectiveListBox.SelectedIndex == -1)
        {
            return;
        }

        //get currently selected electiveID and get list of courses that satisfy it to display
        string electiveID = ElectiveListBox.SelectedItem.Value;
        SatisfyCourseList.Items.Clear();
        List<Dictionary<String, Object>> results;
        results = StoredProcedures.getElectiveChoices(electiveID);
        foreach (Dictionary<String, Object> i in results)
        {
            SatisfyCourseList.Items.Add(new ListItem("" + i["dpt"] + " " + i["num"] + ": " + i["name"] + ", Credits: " + i["credits"], "" + i["courseID"]));
        }

        //Change Content
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        HeaderText.Text = "Add An Elective To Template";
        //setEverything(false, true, false, false, false, false, false, true, false);
        setEverything(false, false, true, false, false, false, false, true, false, false, false);

    }

    ////END OF NEW ADDITIONS

    /// <summary>
    /// CancelButton_Click()
    /// 
    /// Displays the appropriate elements when the user hits the cancel button
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void CancelButton_Click(object sender, EventArgs e)
    {
        //Change Content
        colorStyle.Text = "";
        //This needs to change...
        HeaderText.Text = "List View";
        CourseHeader.Text = "";
        ElectiveCourseHeader.Text = "";
        ElectiveName.Text = "";
        ElectiveCourseList.Items.Clear();
        ElectiveOptionsList.Items.Clear();
        //Change State of elements
        if (ViewRadio.SelectedIndex == 0)
        {
            initializeJavaScript();
            //Change State of Elements
			setEverything(false, false, false, false, true, false, true, false, true, true, false);
        }
        else
        {
            //Display the list view
            generateListViewTable();
            //Change State of Elements
            HeaderText.Text = "List View";
			setEverything(false, false, false, false, false, true, true, false, true, true, false);
        }
    } // end CancelButton_Click()

    /// <summary>
    /// FindCoursesButton_Click()
    /// 
    /// Displays the appropriate elements when the user presses the find courses button in the Add Course page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void FindCoursesButton_Click(object sender, EventArgs e)
    {
        //Error checking (if nothing is selected, then set the selected subject to be the first, which is all courses)
        if (SubjectList.SelectedIndex == -1)
        {
            SubjectList.SelectedIndex = 0;
        }
        //Change State of Elements
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        HeaderText.Text = "Add A Course To " + AdviseeList.SelectedItem.Text + "'s Schedule";
        CancelButton.Text = "Cancel";
		setEverything(false, true, false, false, false, false, false, true, false, false,false);
        CourseHeader.Text = SubjectList.SelectedItem.Text;
        CourseList.Items.Clear();
        //Populate the course list with the appropriate courses
        List<Dictionary<String, Object>> results;
        if (SubjectList.SelectedIndex == 0)
        {
            results = StoredProcedures.getListOfCourses();
        }
        else
        {
            results = StoredProcedures.getListOfCoursesFiltered(SubjectList.SelectedValue); 
        }
        foreach (Dictionary<String, Object> i in results)
        {
            CourseList.Items.Add(new ListItem(""+i["dpt"] + " " + i["num"] + ": "+i["name"] + ", Credits: "+i["credits"], ""+i["courseID"]));
        }
    } // end FindCoursesButton_Click()

    /// <summary>
    /// ElectiveFindCoursesButton_Click()
    /// 
    /// Displays the appropriate elements when the user clicks the find courses button on the elective page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void ElectiveFindCoursesButton_Click(object sender, EventArgs e)
    {
        //Error checking (if nothing is selected, then set the selected subject to be the first, which is all subjects)
        if (ElectiveSubjectList.SelectedIndex == -1)
        {
            ElectiveSubjectList.SelectedIndex = 0;
        }
        //Set the displayed text to be the selected subject
        ElectiveCourseHeader.Text = ElectiveSubjectList.SelectedItem.Text;
        ElectiveOptionsList.Items.Clear();
        List<Dictionary<String, Object>> results;
        //Populate the list of course options appropriately
        if (ElectiveSubjectList.SelectedIndex == 0)
        {
            results = StoredProcedures.getListOfCourses();
        }
        else
        {
            results = StoredProcedures.getListOfCoursesFiltered(ElectiveSubjectList.SelectedValue);
        }
        foreach (Dictionary<String, Object> i in results)
        {
            ElectiveOptionsList.Items.Add(new ListItem("" + i["dpt"] + " " + i["num"] + ": " + i["name"] + ", Credits: " + i["credits"], "" + i["courseID"]));
        }
        //Change State of elements
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        HeaderText.Text = "Add An Elective To " + AdviseeList.SelectedItem.Text + "'s Schedule";
        CancelButton.Text = "Cancel";
		setEverything(false, false, true, false, false, false, false, true, false, false, false);
    } // end ElectiveFindCoursesButton_Click()

    /// <summary>
    /// AddToScheduleButton_Click()
    /// 
    /// Adds a selected course to a student's schedule
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void AddToScheduleButton_Click(object sender, EventArgs e)
    {
        //If either of the necessary items to add a course are not selected, return out
        if(CourseList.SelectedItem == null || YearList.SelectedItem == null)
        {
            //Return to the same add course page and take no additional action
            MessageBox.Show("A course and year must be selected");
            AddCourse_Click(sender, e);
            return;
        }
        Dictionary<String, Object> result = StoredProcedures.getCourse(CourseList.SelectedValue);
        String termCode = SharedFunctions.convertToTermCode(YearList.SelectedItem.Text, SemesterList.SelectedItem.Text);
        if (result != null)
        {
           
            if (StoredProcedures.insertCourseIntoSchedule(AdviseeList.SelectedValue, result["courseID"].ToString(), termCode) == StoredProcedures.FAILURE)
            {
                MessageBox.Show("There was a problem adding the course...");
                //error condition
            }
        }
        else
        {
            //error condition
        }
        //Return to viewing the schedule
        CancelButton_Click(sender, e);
    } // end AddToScheduleButton_Click()

    /// <summary>
    /// ElectiveRemoveButton_Click()
    /// 
    /// Removes a possible course choice from an Elective when on the add elective page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void ElectiveRemoveButton_Click(object sender, EventArgs e)
    {
        if (ElectiveCourseList.SelectedItem == null)
        {
            //Redirect back to the same page
            AddElective_Click(sender, e);
            return;
        }
        ElectiveOptionsList.Items.Add(ElectiveCourseList.SelectedItem);
        ElectiveCourseList.Items.Remove(ElectiveCourseList.SelectedItem);
        ElectiveOptionsList.ClearSelection();
        ElectiveCourseList.ClearSelection();
        //Change State of elements
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        HeaderText.Text = "Add An Elective To " + AdviseeList.SelectedItem.Text + "'s Schedule";
        CancelButton.Text = "Cancel";
		setEverything(false, false, true, false, false, false, false, true, false, false, false);
    } // end ElectiveRemoveButton_Click()

    /// <summary>
    /// ElectiveFinishButtonClick()
    /// 
    /// Creates an elective and adds it to an advisee's schedule
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void ElectiveFinishButton_Click(object sender, EventArgs e)
    {
        if (ElectiveName.Text == "")
        {
            MessageBox.Show("Please supply an elective name");
            AddElective_Click(sender, e);
            return;
            //Response.Redirect(Response.RedirectLocation);
            //return; // need an elective name!
        }
        if (ElectiveCourseList.Items.Count == 0)
        {
            MessageBox.Show("The elective must have at least one possible course");
            AddElective_Click(sender, e);
            return;
           // return; // need a course in the electiveCourseList!
        }
        if (ElectiveManageLabel.Text.Equals(""))
        {
            if (StoredProcedures.makeNewElective(ElectiveName.Text) == StoredProcedures.FAILURE)
            {
                //error condition
                MessageBox.Show("The elective could not be created for some reason...");
            }
            //Get the ID of the elective just made
            int lastElectiveID = SharedFunctions.getLastElectiveID();
            //Get the term code from the user choices
            String term = SharedFunctions.convertToTermCode(ElectiveYearList.SelectedItem.Text, ElectiveSemesterList.SelectedItem.Text);
            // Get the first course in the elective course choice list and set it as the first selected course for the elective
            Dictionary<String, Object> result = StoredProcedures.getCourse(ElectiveCourseList.Items[0].Value);
            //Insert the elective into the schedule
            if (StoredProcedures.insertElectiveIntoSchedule(AdviseeList.SelectedValue, lastElectiveID.ToString(), result["courseID"].ToString(), term) == StoredProcedures.FAILURE)
            {
                //error condition
                MessageBox.Show("The elective could not be added to the schedule for some reason...");
            }

            //Insert all the selected courses into the elective
            foreach (ListItem i in ElectiveCourseList.Items)
            {
                if (StoredProcedures.addCourseToElective(lastElectiveID.ToString(), i.Value) == StoredProcedures.FAILURE)
                {
                    //error condition
                    MessageBox.Show(i.Text + " could not be added to the elective because it already exists in the elective");
                }
            }
        }
        else
        {
            Dictionary<String, Object> result = StoredProcedures.getCourse(ElectiveCourseList.Items[0].Value);
            String adviseeID = AdviseeList.SelectedItem.Value;
            String eid = ElectiveManageLabel.Text;
            String selectedCourseID = ""+result["courseID"];
            String term = SharedFunctions.convertToTermCode(ElectiveYearList.SelectedItem.Text, ElectiveSemesterList.SelectedItem.Text);

            if (StoredProcedures.updateElectiveInSchedule(adviseeID, eid, selectedCourseID, term) == StoredProcedures.FAILURE)
            {
                //error condition
                MessageBox.Show("The elective could not be moved in the schedule");
            }

            List<Dictionary<String, object>> currentChoices = StoredProcedures.getElectiveChoices(eid);
            foreach (ListItem i in ElectiveCourseList.Items)
            {
                bool exists = false;
                foreach (Dictionary<String, object> j in currentChoices)
                {
                    String cid = ""+j["courseID"];
                    if (i.Value.Equals(cid))
                    {
                        exists = true;
                        break;
                    }
                }
                if (exists) continue;
                if (StoredProcedures.addCourseToElective(eid, i.Value) == StoredProcedures.FAILURE)
                {
                    MessageBox.Show(i.Text + " could not be added to the elective because it already exists in the elective");
                    //error condition
                }
            }
            foreach (Dictionary<String, object> j in currentChoices)
            {
                bool exists = false;
                String cid = ""+j["courseID"];
                foreach (ListItem i in ElectiveCourseList.Items)
                {
                    if (i.Value.Equals(cid))
                    {
                        exists = true;
                        break;
                    }
                }
                if (exists) continue;
                if (StoredProcedures.removeCourseFromElective(eid, cid) == StoredProcedures.FAILURE)
                {
                    //error condition
                }
            }
        }
        //Regenerate the proper view
        if (ViewRadio.SelectedIndex == 0)
        {
            initializeJavaScript();
        }
        else
        {
            generateListViewTable();
        }
        CancelButton_Click(sender, e);
    } // end ElectiveFinishButtonClick()

    /// <summary>
    /// ElectiveAddButton_Click()
    /// 
    /// Add a course to the list of the possible courses in an elective on the add elective page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void ElectiveAddButton_Click(object sender, EventArgs e)
    {
        if (ElectiveOptionsList.SelectedItem == null)
        {
            //Redirect to the same page and take no action
            AddElective_Click(sender, e);
            return;
        }
        //add a course to the possible choices for the elective
        ElectiveCourseList.Items.Add(ElectiveOptionsList.SelectedItem);
        ElectiveOptionsList.Items.Remove(ElectiveOptionsList.SelectedItem);
        ElectiveOptionsList.ClearSelection();
        ElectiveCourseList.ClearSelection();
        //Change State of elements
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        HeaderText.Text = "Add An Elective To " + AdviseeList.SelectedItem.Text + "'s Schedule";
        CancelButton.Text = "Cancel";
		setEverything(false, false, true, false, false, false, false, true, false, false, false);
    } // end ElectiveAddButton_Click()

    /// <summary>
    /// ViewNotes_Click()
    /// 
    /// Enables the appropriate elements on the page when the view notes button is clicked
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void ViewNotes_Click(object sender, EventArgs e)
    {
        //Change State of elements
        colorStyle.Text = "";
        HeaderText.Text = "Note";
        CancelButton.Text = "Close";
		setEverything(false, false, false, true, false, false, false, true, false, false, false);
        getNotes();
        //Confused by this...
        if (NoteModeButton.Text.Equals("Add"))
        {
            NoteModeButton_Click(sender, e);
        }
    } // end ViewNotes_Click()

    /// <summary>
    /// NoteSelectionChanged()
    /// 
    /// Called whenever the selected note in the NoteSelectionList is changed and sets the appropriate
    /// elements on the page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void NoteSelectionChanged(object sender, EventArgs e)
    {
        NoteModeButton.Enabled = true;
        NoteRemoveButton.Enabled = true;
        if (NoteSelectionList.SelectedItem == null)
            NoteModeButton.Text = "Add";
        NoteModeButton.Text = "Edit";
        //This isn't working quite right yet!
        getNoteText();
        //Change State of elements
        colorStyle.Text = "";
        HeaderText.Text = "Note";
        CancelButton.Text = "Close";
		setEverything(false, false, false, true, false, false, false, true, false, false, false);
    } // end NoteSelectionChanged()

    /// <summary>
    /// NoteModeButton_Click()
    /// 
    /// Reverse the mode of the NoteMode button from edit to add or vice versa when it is clicked
    /// and populate the edit box with the current note if it is in edit mode
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void NoteModeButton_Click(object sender, EventArgs e)
    {
        if (NoteModeButton.Text.Equals("Edit"))
        {
            NoteModeButton.Text = "Add";
            NoteSubmitButton.Text = "Update Note";
            NoteSubheaderText.Text = "Edit Note";
            NoteInputBox.Text = NoteDisplayBox.Text;
        }
        else
        {
            NoteModeButton.Text = "Edit";
            NoteSubmitButton.Text = "Add";
            NoteSubheaderText.Text = "Add Note";
        }
        //Change State of elements
        colorStyle.Text = "";
        HeaderText.Text = "Note";
        CancelButton.Text = "Close";
		setEverything(false, false, false, true, false, false, false, true, false, false, false);
    }
    /// <summary>
    /// NoteRemoveButton_Click()
    /// 
    /// Removes a selected note from an advisees notes
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void NoteRemoveButton_Click(object sender, EventArgs e)
    {
        if (NoteSelectionList.SelectedItem == null)
        {
            //Return to the same page and take no action
            ViewNotes_Click(sender, e);
            return;
        }
        if (StoredProcedures.removeNote(NoteSelectionList.SelectedValue) == StoredProcedures.FAILURE)
        {
            //error condition
        }
        NoteDisplayBox.Text = "";
        NoteModeButton.Text = "Add";
        getNotes();
        //Change State of elements
        colorStyle.Text = "";
        HeaderText.Text = "Note";
        CancelButton.Text = "Close";
		setEverything(false, false, false, true, false, false, false, true, false, false, false);
    } // end NoteRemoveButton_Click()

    /// <summary>
    /// NoteSubmitButton_Click()
    /// 
    /// Adds a note for an advisee or updates an existing note
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void NoteSubmitButton_Click(object sender, EventArgs e)
    {
        int result;
        if (NoteSubmitButton.Text == "Add")
        {
            //Add a new note
            result = StoredProcedures.addNote(AdviseeList.SelectedValue, NoteInputBox.Text, Session["Advisor_firstName"] + " " + Session["Advisor_lastName"], SharedFunctions.generateKey(AdviseeList.SelectedValue));
        }
        else
        {
            //No note is selected to update - return from the function
            if (NoteSelectionList.SelectedItem == null)
            {
                //Return to the same page and take no action
                NoteModeButton_Click(sender, e);
                return;
            }
            //Update the existing note
            result = StoredProcedures.updateNote(AdviseeList.SelectedValue, NoteSelectionList.SelectedValue, NoteInputBox.Text, Session["Advisor_firstName"] + " " + Session["Advisor_lastName"], SharedFunctions.generateKey(AdviseeList.SelectedValue));
        }
        if (result == StoredProcedures.FAILURE)
        {
            //error condition
        }
        //Set the displayed note to be whatever was just input
        NoteDisplayBox.Text = NoteInputBox.Text;
        //Clear the input box
        NoteInputBox.Text = "";
        if (NoteSubmitButton.Text == "Add")
        {
            //Refresh the notes if a new one was added
            NoteDisplayBox.Text = "";
            getNotes();
        }
        else
        {
            //set the selected index back to what it was
            int selected = NoteSelectionList.SelectedIndex;
            getNotes();
            NoteSelectionList.SelectedIndex = selected;
        }
        //Set the mode buttons back to add
        NoteModeButton.Text = "Edit";
        NoteSubmitButton.Text = "Add";
        NoteSubheaderText.Text = "Add Note";
        NoteSelectionList.SelectedIndex = -1;
        //Change State of elements
        colorStyle.Text = "";
        HeaderText.Text = "Note";
        CancelButton.Text = "Close";
        setEverything(false, false, false, true, false, false, false, true, false, false, false);
            
    } // end NoteSubmitButton_Click()

    /// <summary>
    /// ViewLog_Click()
    /// 
    /// Displays the appropriate elements on the page for an advisee when the view log button is clicked
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void ViewLog_Click(object sender, EventArgs e)
    {
        //Change State of elements
        colorStyle.Text = "";
        HeaderText.Text = "Log";
        CancelButton.Text = "Close";
        setUninitializedView(false);
        setAddCourseView(false);
        setAddElectiveView(false);
        setNotesView(false, true);
        setGraphicalView(false);
        setListView(false);
        setPageControls(false, true, false, false);
        //Display the log entries
        NoteDisplayBox.Text = "";
        List<Dictionary<String, Object>> log = StoredProcedures.getLogEntries(AdviseeList.SelectedValue);
        foreach (Dictionary<String, Object> i in log)
        {
            String date = i["date"].ToString();
            date = date.Substring(0, date.Length - 12);
            NoteDisplayBox.Text = NoteDisplayBox.Text + date + " - " + i["author"] + " Updated" + System.Environment.NewLine;
        }
        NoteDisplayBox.Visible = true;
        NoteDisplayBox.Width = new Unit("99%");
        NoteDisplayBox.Rows = 20;
    } // end ViewLog_Click()

    /// <summary>
    /// SaveButton_Click()
    /// 
    /// Adds a new log entry
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void SaveButton_Click(object sender, EventArgs e)
    {
        //Add a new log entry to indicate the schedule was updated
        StoredProcedures.addLogEntry(AdviseeList.SelectedValue, Session["Advisor_firstName"] + " "+ Session["Advisor_lastName"].ToString());
        generateListViewTable();
    } // end SaveButton_Click()

    /// <summary>
    /// getSelectedRadio()
    /// 
    /// Event handler for radio buttons in list view
    /// </summary>
    /// <param name="sender">object sender - the radio button for which this is the event</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void getSelectedRadio(object sender, EventArgs e)
    {
        RadioButton rb = (RadioButton)sender;
        //Set an invisible field to be referred to later to determine the selected radio button
        ListViewSelectedCourse.Text = rb.ID;
    } //end getSelectedRadio()

    /// <summary>
    /// chooseElectiveOption()
    /// 
    /// Selects an elective from the drop down list of valid options
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void chooseElectiveOption(object sender, EventArgs e)
    {
        DropDownList db = sender as DropDownList;
        String adviseeID = (String)Session["Advisor_adviseeIDGV"];
        String[] electiveIDAndTerm = db.ID.Split('%');
        if (StoredProcedures.updateElectiveSelectedCourseInSchedule(adviseeID, electiveIDAndTerm[0], electiveIDAndTerm[2], "" + db.SelectedItem.Value) == StoredProcedures.FAILURE)
        {
            MessageBox.Show("The course you are trying to select for this elective is currently chosen for a different instance of this elective.");
        }
        initializeJavaScript();
    } //end chooseElectiveOption()

    /// <summary>
    /// LeftButton_Click()
    /// Graphical View Function
    /// 
    /// Decrement the year if possible
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void LeftButton_Click(object sender, EventArgs e)
    {
        int year = Convert.ToInt32((String)Session["Advisor_yearGV"]);
        String sd = StartDate.Text.Substring(StartDate.Text.IndexOf(' '));
        int minYear = Convert.ToInt32(sd);
        if (StartDate.Text.Substring(0, StartDate.Text.IndexOf(' ')) == "Spring")
        {
            minYear--;
        }
        else if (StartDate.Text.Substring(0, StartDate.Text.IndexOf(' ')) == "Summer")
        {
            minYear--;
        }
        if (year >= minYear) year = year - 1;
        Session["Advisor_yearGV"] = "" + year;
        initializeJavaScript();
    } //end LeftButton_Click()

    /// <summary>
    /// RightButton_Click()
    /// Graphical View Function
    /// 
    /// Increment the year if possible
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void RightButton_Click(object sender, EventArgs e)
    {
        int year = Convert.ToInt32((String)Session["Advisor_yearGV"]);
        String sd = StartDate.Text.Substring(StartDate.Text.IndexOf(' '));
        int maxYear = Convert.ToInt32(sd)+7;
        if (year < maxYear) year = year + 1;
        Session["Advisor_yearGV"] = "" + year;
        initializeJavaScript();
    } //end RightButton_Click()

    /// <summary>
    /// colorViolations
    ///
    /// POSSIBLE Color Values:
    ///  PASS (NO COLORING)
    ///  BORDERLINE (FCB315) //Pale Yellow (60)
    ///  FAIL (AB1E38) //Red (50)
    ///  
    /// preReq/coReq (F15E22) Orange
    /// 
    ///  NULL (NULL GRADE, RIGHT SPOT) (COLORED)    CACBC8 white/cream
    ///  MISSING (NO RECORD OF COURSE) (COLORED)   727075 grey
    ///  WRONG(COURSE RECORD IN DIFFERENT TERM, PREVIOUS OR ) (COLORED) Black 000000 
    ///  
    ///  
    /// Color those methods that are flagged for violation(s)
    /// </summary>
    /// <param name="preCoReqColoring"></param>
    public void colorViolations(Dictionary<String, Object> violations)
    {
        foreach (Control p in GraphicalViewPanel.Controls)
        {
            foreach (Control c in p.Controls)
            {
                if (c is Panel)
                {
                    foreach (Control courseBox in c.Controls)
                    {
                        if (courseBox is Panel)
                        {
                            String courseID = ((Panel)courseBox).ID.Substring(courseBox.ID.IndexOf("$") + 1);
                            if (violations.ContainsKey(courseID))
                            {
                                String courseViolation = (String)((Dictionary<String, Object>)violations[courseID])["violation"];
                                if (courseViolation == "FAIL")
                                {
                                    ((Panel)courseBox).CssClass = "courseFailCSS";
                                }
                                else if (courseViolation == "BORDERLINE")
                                {
                                    ((Panel)courseBox).CssClass = "courseBorderlineCSS";
                                }
                                else if (courseViolation == "preReq" || courseViolation == "coReq")
                                {
                                    ((Panel)courseBox).CssClass = "precoreqViolationsCSS";
                                }
                                else if (courseViolation == "NULL")
                                {
                                    ((Panel)courseBox).CssClass = "courseNullCSS";
                                }
                                else if (courseViolation == "MISSING")
                                {
                                    ((Panel)courseBox).CssClass = "courseMissingCSS";
                                }
                                else if (courseViolation == "WRONG")
                                {
                                    ((Panel)courseBox).CssClass = "courseWrongCSS";
                                }
                                else
                                {
                                    ((Panel)courseBox).CssClass = "courseLabelCSS";
                                }

                            }
                            else
                            {
                                ((Panel)courseBox).CssClass = "courseLabelCSS";
                            }
                        }
                    }
                }
            }//end of foreach Control
        }//end foreach Panel
        return;
    }//end colorViolations()

    /////////////////////////////////////////
    //Web Functions                        //
    // - Require the [WebMethod] tag       //
    // - These are available to JavaScript //
    /////////////////////////////////////////

    /// <summary>
    /// MoveCourse()
    /// Graphical View Function
    /// 
    /// Called when user drops a course on a semester region in GV.
    /// </summary>
    /// <param name="crn">String crn - course ID number, prefaced with the type (c for course, e for elective)</param>
    /// <param name="sem">String sem - the semester region that course was dropped into</param>
    [WebMethod]
    public static void MoveCourse(String crn, String sem)
    {
        //Get the semester region the course was dropped into
        int semester = Convert.ToInt32(sem);
        //Get the currently visible year and the next two
        int y = Convert.ToInt32((String)HttpContext.Current.Session["Advisor_yearGV"]);
        int y1 = y + 1;
        int y2 = y + 2;
        //Get the advisee ID
        String adviseeID = (String)HttpContext.Current.Session["Advisor_adviseeIDGV"];

        //Determine the term from the semester region and currently visible year
        String term = "";
        switch (semester)
        {
            case 1:
                term = SharedFunctions.convertToTermCode("" + y, "Fall");
                break;
            case 2:
                term = SharedFunctions.convertToTermCode("" + y1, "Spring");
                break;
            case 3:
                term = SharedFunctions.convertToTermCode("" + y1, "Summer");
                break;
            case 4:
                term = SharedFunctions.convertToTermCode("" + y1, "Fall");
                break;
            case 5:
            default:
                term = SharedFunctions.convertToTermCode("" + y2, "Spring");
                break;
        }
        //Ensure term code is accurate length
        int numZeros = 6 - term.Length;
        for (int i = 0; i < numZeros; i++)
        {
            term = "0" + term;
        }

        //Get the course ID (and the selected course ID for electives)
        String courseID = "";
        String selectedCourseID = "";
        //If the dropped box is a course
        if (crn[0] == 'c') //i.e. the id of the box is prefaced with a 'c'
        {
            //Update the database
            courseID = crn.Substring(1);
            if (StoredProcedures.updateCourseInSchedule(adviseeID, courseID, term) == StoredProcedures.FAILURE)
            {
                MessageBox.Show("Could not move the course");
            }
        }
        else //The dropped box is an elective (prefaced with 'e')
        {
            //The elective ID is before the 's', and the selected course ID is after
            int sloc = crn.IndexOf('s');
            selectedCourseID = crn.Substring(sloc + 1);
            courseID = crn.Substring(1, (sloc - 1));
            //Update the database
            if (StoredProcedures.updateElectiveTermInSchedule(adviseeID, courseID, selectedCourseID, term) == StoredProcedures.FAILURE)
            {
                MessageBox.Show("Could not move the elective");
            }
        }
    } //end MoveCourse()

    /////////////////////
    //Private Functions//
    /////////////////////

    /// <summary>
    /// setUninitializedView()
    /// 
    /// Sets web controls for uninitialized view to appropriate state.
    /// </summary>
    /// <param name="state">bool state - whether uninitialized view is to be displayed or not</param>
    private void setUninitializedView(bool state)
    {
        //Related elements
        UninitTable1.Visible = state;
        UninitTable1.Enabled = state;
        UninitTable2.Visible = state;
        UninitTable2.Enabled = state;
    } //end setUninitializedView()

    /// <summary>
    /// setAddCourseView()
    /// 
    /// Sets web controls for add course view to appropriate state.
    /// </summary>
    /// <param name="state">bool state - whether course view is to be displayed or not</param>
    private void setAddCourseView(bool state)
    {
        //Related elements
        AddCourseTable1.Visible = state;
        AddCourseTable1.Enabled = state;
        AddCourseTable2.Visible = state;
        AddCourseTable2.Enabled = state;
    } //end setAddCourseView()

    /// <summary>
    /// setAddElectiveView()
    /// 
    /// Sets web controls for add elective view to appropriate state.
    /// </summary>
    /// <param name="state">bool state - whether elective view is to be displayed or not</param>
    private void setAddElectiveView(bool state)
    {
        //Related elements
        AddExistingElectiveTable1.Visible = state;
        AddExistingElectiveTable1.Enabled = state;
    } //end setAddElectiveView()

    /// <summary>
    /// setCreateElectiveView()
    /// 
    /// Sets web control for create elective view to appropriate state.
    /// To be used in the add existing elective table.
    /// </summary>
    /// <param name="state"></param>
    private void setCreateElectiveView(bool state)
    {
        //Related Elements, tables called AddElective because
        //that was original name/purpose
        AddElectiveTable1.Visible = state;
        AddElectiveTable1.Enabled = state;
        AddElectiveTable2.Visible = state;
        AddElectiveTable2.Enabled = state;
        AddElectiveTable3.Visible = state;
        AddElectiveTable3.Enabled = state;
        AddElectiveLowerHeader.Visible = state;
        AddElectiveLowerHeader.Enabled = state;
    }

    /// <summary>
    /// setNotesView()
    /// 
    /// Sets web controls for notes view to appropriate state.
    /// </summary>
    /// <param name="state">bool state - whether notes view is to be displayed or not</param>
    private void setNotesView(bool state)
    {
        //Call the overridden method with Log disabled
        setNotesView(state, false);
    } //end setNotesView()

    /// <summary>
    /// setNotesView()
    /// 
    /// Sets web controls for notes view to appropriate state.
    /// </summary>
    /// <param name="state">bool state - whether notes view is to be displayed or not</param>
    /// <param name="state">bool logState - whether log view is to be displayed or not</param>
    private void setNotesView(bool state, bool logState)
    {
        //Related elements
        NoteSelectionList.Visible = state;
        NoteSelectionList.Enabled = state;
        NoteSubheader.Visible = state;
        NoteSubheader.Enabled = state;
        NoteInputBox.Visible = state;
        NoteInputBox.Enabled = state;
        NoteModeButton.Visible = state;
        NoteModeButton.Enabled = state;
        NoteRemoveButton.Visible = state;
        NoteRemoveButton.Enabled = state;
        //Log elements
        NoteDisplayBox.Visible = (state || logState);
    } //end setNotesView()

    /// <summary>
    /// setGraphicalView()
    /// 
    /// Sets web controls for graphical view to appropriate state.
    /// </summary>
    /// <param name="state">bool state - whether graphical view is to be displayed or not</param>
    private void setGraphicalView(bool state)
    {
        //Related elements
        GraphicalViewPanel.Enabled = state;
        GraphicalViewPanel.Visible = state;
        LeftButton.Enabled = state;
        LeftButton.Visible = state;
        RightButton.Enabled = state;
        RightButton.Visible = state;
    } //end setGraphicalView()

    /// <summary>
    /// setListView()
    /// 
    /// Sets web controls for list view to appropriate state.
    /// </summary>
    /// <param name="state">bool state - whether list view is to be displayed or not</param>
    private void setListView(bool state)
    {
        //Related elements
        ListViewPanel.Visible = state;
        ListViewPanel.Enabled = state;
        ListViewOptionsTable.Visible = state;
        ListViewOptionsTable.Enabled = state;
    } //end setListView()

    /// <summary>
    /// setPageControls()
    /// 
    /// Sets miscellaneous web controls to appropriate state.
    /// </summary>
    /// <param name="state">bool state - whether typical controls are to be displayed or not</param>
    /// <param name="state">bool cancelState - whether cancel button is to be displayed or not</param>
    /// <param name="state">bool homeState - whether home button is enabled or not</param>
    /// <param name="state">bool cancelState - whether advisee list is enabled or not</param>
    private void setPageControls(bool state, bool cancelState, bool homeState, bool listState)
    {
        //Other page elements
        ReinitializeSchedule.Enabled = state;
        AddCourse.Enabled = state;
        CreateElective.Enabled = state;
        ViewRadio.Enabled = state;
        SaveButton.Enabled = state;
        PrintButton.Enabled = state;
        ViewLog.Enabled = state;
        ViewNotes.Enabled = state;
        //Cancel Button
        CancelButton.Enabled = cancelState;
        CancelButton.Visible = cancelState;
        //Home Button
        HomeButton.Enabled = homeState;
        //Advisee List
        AdviseeList.Enabled = listState;
    } //end setPageControls()

    /// <summary>
    /// populateCourses()
    /// 
    /// Gets all the courses in an advisee's schedule (the selected advisee in the drop down list) and returns them in a list of courses
    /// </summary>
    /// <returns>A list of all the courses in the student's schedule</returns>
    private List<Course> populateCourses()
    {
        //Get all courses from database and add them to a new list
        List<Course> courses = new List<Course>();
        List<Dictionary<String, Object>> results = StoredProcedures.getScheduleCourseInfo(AdviseeList.SelectedValue);
        foreach (Dictionary<String, Object> i in results)
        {
            Course newCourse = new Course("" + i["courseID"], "" + i["dpt"], "" + i["num"], "" + i["name"], Convert.ToDouble(i["credits"]), "" + i["term"]);
            courses.Add(newCourse);
        }
        return courses;
    } //end populateCourses()

    /// <summary>
    /// populateElectives()
    /// 
    /// Gets all the electives in an advisee's schedule (the selected value in the drop down list) and returns them in a list of electives
    /// </summary>
    /// <returns>A list of all the electives in the student's schedule</returns>
    private List<Elective> populateElectives()
    {
        //Get all electives from database and add them to a new list
        List<Elective> electives = new List<Elective>();
        List<Dictionary<String, Object>> results = StoredProcedures.getScheduleElectiveInfo(AdviseeList.SelectedValue);
        foreach (Dictionary<String, Object> i in results)
        {
            Course newCourse = new Course("" + i["selectedCourseID"], "" + i["dpt"], "" + i["num"], "" + i["name"], Convert.ToDouble(i["credits"]), "" + i["term"]);
            Elective newElective = new Elective(Convert.ToInt32(i["electiveID"]), "" + i["electiveName"], newCourse);
            List<Dictionary<String, Object>> results2 = StoredProcedures.getElectiveChoices(newElective.getElectiveID().ToString());
            foreach (Dictionary<String, Object> i2 in results2)
            {
                Course newCourseInElective = new Course("" + i2["courseID"], "" + i2["dpt"], "" + i2["num"], "" + i2["name"], Convert.ToDouble(i2["credits"]), "" + i["term"]);
                newElective.addCourse(newCourseInElective);
            }
            electives.Add(newElective);
        }
        return electives;
    } //end populateElectives()

    /// <summary>
    /// getNotes()
    /// 
    /// Get all the notes in a student's schedule and adds them to the NoteSelectionList
    /// </summary>
    private void getNotes()
    {
        List<Dictionary<String, Object>> results = StoredProcedures.getNotes(AdviseeList.SelectedValue, SharedFunctions.generateKey(AdviseeList.SelectedValue));
        //Get the notes in the database and display them in the notes area
        NoteSelectionList.Items.Clear();
        foreach (Dictionary<String, Object> i in results)
        {
            //Take off the timestamp (just want the date)
            String date = i["date"].ToString();
            date = date.Substring(0, date.Length - 12);
            String itemText = i["author"] + ", " + date + System.Environment.NewLine;
            NoteSelectionList.Items.Add(new ListItem(itemText, "" + i["noteID"]));
        }
        NoteDisplayBox.Text = "";
    } // end getNotes()

    /// <summary>
    /// getNoteText()
    /// 
    /// Gets the text of a single note (the currently selected note)
    /// </summary>
    private void getNoteText()
    {
        Dictionary<String, Object> result = StoredProcedures.getSingleNote(NoteSelectionList.SelectedValue, AdviseeList.SelectedValue, SharedFunctions.generateKey(AdviseeList.SelectedValue));
        if (result != null)
        {
            NoteDisplayBox.Text = "" + result["note"];
        }
    } // end getNoteText()

    /// <summary>
    /// initializeJavaScript()
    /// Graphical View Function
    /// 
    /// Initializes and dynamically creates the pageLoad function for JavaScript and course boxes.
    /// </summary>
    private void initializeJavaScript()
    {
        //Set header of main box to display visible years
        int y = Convert.ToInt32((String)Session["Advisor_yearGV"]);
        int y2 = y + 2;
        HeaderText.Text = "Years " + y + " - " + y2;

        //Populate lists of courses and electives
        Session["Advisor_adviseeIDGV"] = AdviseeList.SelectedItem.Value;
        courseList = populateCourses();
        electiveList = populateElectives();

        //Clear semester regions to ensure always starting fresh
        clearSemesterRegions();

        //Dynamic JavaScript - begin HTML script tag and begin pageLoad function
        JavaScriptPageLoad.Text = "<script type='text/javascript'> function pageLoad() { ";
        //Initialize each part of GV and its associated JavaScript
        initializeSemesterRegions();
        initializeCourseBoxes();
        initializeElectiveBoxes();
        initializeSemesterLabels();
        finalizeSemesterRegions();
        //Dynamic JavaScript - end the pageLoad function and end the HTML tag
        JavaScriptPageLoad.Text += "} </script>";

        Dictionary<String, Object> optimizer = SharedFunctions.checkSchedule(AdviseeList.SelectedValue, populateCourses(), populateElectives());
        colorViolations(optimizer);
        SharedFunctions.displayViolations(ViolationsLabel, (List<String>)optimizer["violationMessages"]);
    } //end initializeJavaScript()

    /// <summary>
    /// clearSemesterRegions()
    /// Graphical View Function
    /// 
    /// Resets semester regions and removes all course boxes and labels.
    /// </summary>
    private void clearSemesterRegions()
    {
        //Clear old courses
        SemesterRegion1.Controls.Clear();
        SemesterRegion2.Controls.Clear();
        SemesterRegion3.Controls.Clear();
        SemesterRegion4.Controls.Clear();
        SemesterRegion5.Controls.Clear();
        //Re-add center style
        SemesterRegion1.Controls.Add(new LiteralControl("<center>"));
        SemesterRegion2.Controls.Add(new LiteralControl("<center>"));
        SemesterRegion3.Controls.Add(new LiteralControl("<center>"));
        SemesterRegion4.Controls.Add(new LiteralControl("<center>"));
        SemesterRegion5.Controls.Add(new LiteralControl("<center>"));
        //Re-add labels
        SemesterRegion1.Controls.Add(SemesterLabel1);
        SemesterRegion2.Controls.Add(SemesterLabel2);
        SemesterRegion3.Controls.Add(SemesterLabel3);
        SemesterRegion4.Controls.Add(SemesterLabel4);
        SemesterRegion5.Controls.Add(SemesterLabel5);
        //Re-add Credit Labels
        SemesterRegion1.Controls.Add(SemesterCreditsLabel1);
        SemesterRegion2.Controls.Add(SemesterCreditsLabel2);
        SemesterRegion3.Controls.Add(SemesterCreditsLabel3);
        SemesterRegion4.Controls.Add(SemesterCreditsLabel4);
        SemesterRegion5.Controls.Add(SemesterCreditsLabel5);
        //Re-initialize credits labels
        SemesterCreditsLabel1.Text = "Credits: 0";
        SemesterCreditsLabel2.Text = "Credits: 0";
        SemesterCreditsLabel3.Text = "Credits: 0";
        SemesterCreditsLabel4.Text = "Credits: 0";
        SemesterCreditsLabel5.Text = "Credits: 0";
        //Re-add move labels
        SemesterRegion1.Controls.Add(new LiteralControl("<span id=\"SemMove1\">Moving...</span></center>"));
        SemesterRegion2.Controls.Add(new LiteralControl("<span id=\"SemMove2\">Moving...</span></center>"));
        SemesterRegion3.Controls.Add(new LiteralControl("<span id=\"SemMove3\">Moving...</span></center>"));
        SemesterRegion4.Controls.Add(new LiteralControl("<span id=\"SemMove4\">Moving...</span></center>"));
        SemesterRegion5.Controls.Add(new LiteralControl("<span id=\"SemMove5\">Moving...</span></center>"));
    } //end clearSemesterRegions()

    /// <summary>
    /// finalizeSemesterRegions()
    /// Graphical View Function
    /// 
    /// Calculates and adds padding to semester regions and adds the bottom semester labels.
    /// </summary>
    private void finalizeSemesterRegions()
    {
        //count maximum number of panels in each semester region
        int max = 0;
        int[] counts = { 0, 0, 0, 0, 0 };
        foreach (Control c in SemesterRegion1.Controls)
        {
            if (c is Panel) counts[0] = counts[0] + 1;
        }
        if (counts[0] > max) max = counts[0];
        foreach (Control c in SemesterRegion2.Controls)
        {
            if (c is Panel) counts[1] = counts[1] + 1;
        }
        if (counts[1] > max) max = counts[1];
        foreach (Control c in SemesterRegion3.Controls)
        {
            if (c is Panel) counts[2] = counts[2] + 1;
        }
        if (counts[2] > max) max = counts[2];
        foreach (Control c in SemesterRegion4.Controls)
        {
            if (c is Panel) counts[3] = counts[3] + 1;
        }
        if (counts[3] > max) max = counts[3];
        foreach (Control c in SemesterRegion5.Controls)
        {
            if (c is Panel) counts[4] = counts[4] + 1;
        }
        if (counts[4] > max) max = counts[4];

        //Set maximum height of each semester region appropriately
        max = (max / 4) + 1;
        max = max * 100;
        SemesterRegion1.Style["height"] = max + "%";
        SemesterRegion2.Style["height"] = max + "%";
        SemesterRegion3.Style["height"] = max + "%";
        SemesterRegion4.Style["height"] = max + "%";
        SemesterRegion5.Style["height"] = max + "%";

        //Add filler boxes to pad each region
        for (int index = 0; index < 5; index++)
        {
            int limit = max / 100;
            limit = limit * 4;
            limit = limit - 1;
            limit = limit - counts[index];
            for (int i = 0; i < limit; i++)
            {
                Panel p = new Panel();
                p.CssClass = "courseFillerCSS";
                switch (index)
                {
                    case 0:
                        SemesterRegion1.Controls.Add(p);
                        SemesterRegion1.Controls.Add(new LiteralControl("<br />"));
                        break;
                    case 1:
                        SemesterRegion2.Controls.Add(p);
                        SemesterRegion2.Controls.Add(new LiteralControl("<br />"));
                        break;
                    case 2:
                        SemesterRegion3.Controls.Add(p);
                        SemesterRegion3.Controls.Add(new LiteralControl("<br />"));
                        break;
                    case 3:
                        SemesterRegion4.Controls.Add(p);
                        SemesterRegion4.Controls.Add(new LiteralControl("<br />"));
                        break;
                    case 4:
                    default:
                        SemesterRegion5.Controls.Add(p);
                        SemesterRegion5.Controls.Add(new LiteralControl("<br />"));
                        break;
                }
            }
        }

        //Add center style
        SemesterRegion1.Controls.Add(new LiteralControl("<br /><center>"));
        SemesterRegion2.Controls.Add(new LiteralControl("<br /><center>"));
        SemesterRegion3.Controls.Add(new LiteralControl("<br /><center>"));
        SemesterRegion4.Controls.Add(new LiteralControl("<br /><center>"));
        SemesterRegion5.Controls.Add(new LiteralControl("<br /><center>"));

        //Add labels with following properties:
        //Enabled="false" BorderStyle="None" Width="90%" CssClass="labelCSS"
        for (int i = 1; i <= 5; i++)
        {
            TextBox slc = new TextBox();
            slc.Enabled = false;
            slc.BorderStyle = BorderStyle.None;
            slc.Width = new Unit("90%");
            slc.CssClass = "labelCSS";
            switch (i)
            {
                case 1:
                    slc.Text = SemesterLabel1.Text;
                    SemesterRegion1.Controls.Add(slc);
                    break;
                case 2:
                    slc.Text = SemesterLabel2.Text;
                    SemesterRegion2.Controls.Add(slc);
                    break;
                case 3:
                    slc.Text = SemesterLabel3.Text;
                    SemesterRegion3.Controls.Add(slc);
                    break;
                case 4:
                    slc.Text = SemesterLabel4.Text;
                    SemesterRegion4.Controls.Add(slc);
                    break;
                case 5:
                default:
                    slc.Text = SemesterLabel5.Text;
                    SemesterRegion5.Controls.Add(slc);
                    break;
            }

        }

        //End center styling
        SemesterRegion1.Controls.Add(new LiteralControl("</center>"));
        SemesterRegion2.Controls.Add(new LiteralControl("</center>"));
        SemesterRegion3.Controls.Add(new LiteralControl("</center>"));
        SemesterRegion4.Controls.Add(new LiteralControl("</center>"));
        SemesterRegion5.Controls.Add(new LiteralControl("</center>"));
    } //end finalizeSemesterRegions()

    /// <summary>
    /// initializeCourseBoxes()
    /// Graphical View Function
    /// 
    /// Dynamically creates course boxes and places them in the appropriate semester containers.
    /// </summary>
    private void initializeCourseBoxes()
    {
        //Get currently visible year
        int y = Convert.ToInt32((String)Session["Advisor_yearGV"]);
        foreach (Course c in courseList)
        {
            //Get relevant course info
            String term = c.getSemester();
            int cyear = c.getYear();
            String deptNum = c.getDpt() + c.getNum();
            String termCode = SharedFunctions.convertToTermCode((String)Session["Advisor_yearGV"], term);

            //If current course is not within currently visible years, then skip over it
            if ((cyear < y) || (cyear > (y + 2))) continue;

            //Determine place of course on schedule
            if (cyear == y)
            {
                if (!term.Equals("Fall")) continue; //Only fall of first year is visible
                createCourseBox(c.getCourseID(), deptNum, c.getName(), c.getCredits(), 1, termCode);
                UpdateSemesterCreditsLabel(1, c.getCredits());
            }
            else if (cyear == (y + 1))
            {
                if (term.Equals("Spring"))
                {
                    createCourseBox(c.getCourseID(), deptNum, c.getName(), c.getCredits(), 2, termCode); //Spring of second visible year
                    UpdateSemesterCreditsLabel(2, c.getCredits());
                }
                else if (term.Equals("Summer"))
                {
                    createCourseBox(c.getCourseID(), deptNum, c.getName(), c.getCredits(), 3, termCode); //Summer
                    UpdateSemesterCreditsLabel(3, c.getCredits());
                }
                else
                {
                    createCourseBox(c.getCourseID(), deptNum, c.getName(), c.getCredits(), 4, termCode); //Fall
                    UpdateSemesterCreditsLabel(4, c.getCredits());
                }
            }
            else //if (cyear == (y + 2))
            {
                if (!term.Equals("Spring")) continue; //Only spring of third year is visible
                createCourseBox(c.getCourseID(), deptNum, c.getName(), c.getCredits(), 5, termCode);
                UpdateSemesterCreditsLabel(5, c.getCredits());
            }
        }
    } //end initializeCourseBoxes()

    /// <summary>
    /// initializeElectiveBoxes()
    /// Graphical View Function
    /// 
    /// Dynamically creates elective boxes and places them in the appropriate semester containers.
    /// </summary>
    private void initializeElectiveBoxes()
    {
        //Get currently visible year
        int y = Convert.ToInt32((String)Session["Advisor_yearGV"]);
        foreach (Elective e in electiveList)
        {
            //Get relevant elective info
            String term = e.getSemester();
            int eyear = e.getYear();

            //If current elective is not within currently visible years, then skip over it
            if ((eyear < y) || (eyear > (y + 2))) continue;

            //Determine place of elective on schedule
            if (eyear == y)
            {
                if (!term.Equals("Fall")) continue; //Only fall of first year is visible
                createElectiveBox(e.getElectiveID(), e.getElectiveName(), e.getTerm(), e.getCredits(), e.getCourses(), e.getSelectedCourseID(), 1);
                UpdateSemesterCreditsLabel(1, e.getCredits());
            }
            else if (eyear == (y + 1))
            {
                if (term.Equals("Spring"))
                {
                    createElectiveBox(e.getElectiveID(), e.getElectiveName(), e.getTerm(), e.getCredits(), e.getCourses(), e.getSelectedCourseID(), 2); //Spring of second visible year
                    UpdateSemesterCreditsLabel(2, e.getCredits());
                }
                else if (term.Equals("Summer"))
                {
                    createElectiveBox(e.getElectiveID(), e.getElectiveName(), e.getTerm(), e.getCredits(), e.getCourses(), e.getSelectedCourseID(), 3); //Summer
                    UpdateSemesterCreditsLabel(3, e.getCredits());
                }
                else
                {
                    createElectiveBox(e.getElectiveID(), e.getElectiveName(), e.getTerm(), e.getCredits(), e.getCourses(), e.getSelectedCourseID(), 4); //Fall
                    UpdateSemesterCreditsLabel(4, e.getCredits());
                }
            }
            else //if (eyear == (y + 2))
            {
                if (!term.Equals("Spring")) continue; //Only spring of third year is visible
                createElectiveBox(e.getElectiveID(), e.getElectiveName(), e.getTerm(), e.getCredits(), e.getCourses(), e.getSelectedCourseID(), 5);
                UpdateSemesterCreditsLabel(5, e.getCredits());
            }
        }
    } //end initializeElectiveBoxes()

    /// <summary>
    /// initializeSemesterLabels()
    /// Graphical View Function
    /// 
    /// Set semester labels to display the correct semester information.
    /// </summary>
    private void initializeSemesterLabels()
    {
        //Get currently visible years
        int startYear = Convert.ToInt32(SharedFunctions.getAdviseeStartYear((String)Session["Advisor_adviseeIDGV"]));
        //advisee  start year is 1 less than year in term code if they start in the spring/summer
        if (! (SharedFunctions.getAdviseeStartSemester((String)Session["Advisor_adviseeIDGV"]) == "Fall"))
        {
            startYear--;
        }
        int y = Convert.ToInt32((String)Session["Advisor_yearGV"]);
        int y1 = y + 1;
        int y2 = y + 2;
        //Initialize labels
        if (y < startYear)
        {
            SemesterLabel1.Text = "Transfer Credits";
            SemesterLabel2.Text = "Transfer Credits";
            SemesterLabel3.Text = "Transfer Credits";
        }
        else // at least start year
        {
            SemesterLabel1.Text = "Fall " + y;
            SemesterLabel2.Text = "Spring " + y1;
            SemesterLabel3.Text = "Summer " + y1;
        }
        SemesterLabel4.Text = "Fall " + y1;
        SemesterLabel5.Text = "Spring " + y2;
    } //end initializeSemesterLabels()

    /// <summary>
    /// initializeSemesterRegions()
    /// Graphical View Function
    /// 
    /// Create JavaScript code for initializing semester regions as drop targets.
    /// </summary>
    private void initializeSemesterRegions()
    {
        for (int i = 1; i <= 5; i++)
        {
            //Dynamic JavaScript - create code for each drop target
            JavaScriptPageLoad.Text += "var target" + i + " = new AdviseUP.UI.SemesterRegion($get('MainBox_SemesterRegion" + i + "'), '" + i + "'); ";
            JavaScriptPageLoad.Text += "target" + i + ".initialize(); ";
        }
    } //end initializeSemesterRegions()

    /// <summary>
    /// createCourseBox()
    /// Graphical View Function
    /// 
    /// Create an individual course box with ASP.NET web controls.
    /// Also, create JavaScript code for initializing the course box as a drag source.
    /// </summary>
    /// <param name="courseID">String courseID - the unique course ID in the database</param>
    /// <param name="deptNum">String deptNum - the department and number of the course (e.g. CS203)</param>
    /// <param name="courseName">String courseName - the name of the course</param>
    /// <param name="credits">double credits - the number of credits for the course</param>
    /// <param name="regionNumber">int regionNumber - the semester region that the course is currently located (1 through 5)</param>
    /// <param name="term">String term - the term that the course is in</param>
    private void createCourseBox(String courseID, String deptNum, String courseName, double credits, int regionNumber, String term)
    {
        //Create each container and control, placing appropriate controls in the right container
        //Outer Panel (Container, White, Non-Draggable)
        Panel p = new Panel();
        p.CssClass = "courseCSS";
        //Inner Panel (Container, Blue, Draggable, inside Outer Panel)
        Panel cb = new Panel();
        cb.ID = "CourseBoxc$" + courseID;
        cb.CssClass = "courseLabelCSS";
        //Course Name Text (inside Inner Panel)
        Literal lit = new Literal();
        lit.Text = "<span style=\"font-size:12px;\">" + deptNum + " (" + credits + ")" + "</span><br />";
        lit.Text += "<span>" + courseName + "</span>";
        //Manage Course Button (inside Outer Panel)
        Button bb1 = new Button();
        bb1.Text = "Manage";
        bb1.ID = "mnc" + courseID;
        bb1.CssClass = "courseButtonCSS";
        bb1.Click += new EventHandler(ManageCourseButtonGV_Click);
        Button bb2 = new Button();
        bb2.Text = "Remove";
        bb2.ID = "rmc" + courseID;
        bb2.CssClass = "courseButtonCSS";
        bb2.OnClientClick = "javascript:return confirm('Are you sure you want to remove this course?');";
        bb2.Click += new EventHandler(RemoveCourseButtonGV_Click);
        //Add controls to Inner Panel
        cb.Controls.Add(lit);
        //Add controls to Outer Panel
        p.Controls.Add(cb);
        p.Controls.Add(new LiteralControl("<center>"));
        p.Controls.Add(bb1);
        p.Controls.Add(new LiteralControl("&nbsp;"));
        p.Controls.Add(bb2);
        p.Controls.Add(new LiteralControl("</center>"));

        //Add course to correct semester region
        switch (regionNumber)
        {
            case 1:
                SemesterRegion1.Controls.Add(p);
                SemesterRegion1.Controls.Add(new LiteralControl("<br /><br />"));
                break;
            case 2:
                SemesterRegion2.Controls.Add(p);
                SemesterRegion2.Controls.Add(new LiteralControl("<br /><br />"));
                break;
            case 3:
                SemesterRegion3.Controls.Add(p);
                SemesterRegion3.Controls.Add(new LiteralControl("<br /><br />"));
                break;
            case 4:
                SemesterRegion4.Controls.Add(p);
                SemesterRegion4.Controls.Add(new LiteralControl("<br /><br />"));
                break;
            case 5:
            default:
                SemesterRegion5.Controls.Add(p);
                SemesterRegion5.Controls.Add(new LiteralControl("<br /><br />"));
                break;
        }

        //Dynamic JavaScript - create code for drag source
        JavaScriptPageLoad.Text += "var sourceC" + courseID + " = new AdviseUP.UI.CourseBox($get('MainBox_CourseBoxc$" + courseID + "'), 'c" + courseID + "'); ";
        JavaScriptPageLoad.Text += "sourceC" + courseID + ".initialize();";
    } //end createCourseBox()

    /// <summary>
    /// createElectiveBox()
    /// Graphical View Function
    /// 
    /// Create an individual elective box with ASP.NET web controls.
    /// Also, create JavaScript code for initializing the elective box as a drag source.
    /// </summary>
    /// <param name="electiveID">int electiveID - the unique database ID of the elective</param>
    /// <param name="electiveName">String electiveName - the name of the elective</param>
    /// <param name="term">String term - the current term of the elective</param>
    /// <param name="credits">double credits - the number of credits that the selected course is worth</param>
    /// <param name="choiceList">Dictionary(int, Course) choiceList - the list of elective choices</param>
    /// <param name="selectedCourseID">int selectedCourseID - the unique database ID of the currently selected course</param>
    /// <param name="regionNumber">int regionNumber - the semester region that the course is currently located (1 through 5)</param>
    private void createElectiveBox(int electiveID, String electiveName, String term, double credits, Dictionary<String, Course> choiceList, String selectedCourseID, int regionNumber)
    {
        //Create each container and control, placing appropriate controls in the right container
        //Outer Panel (Container, White, Non-Draggable)
        Panel p = new Panel();
        p.CssClass = "electiveCSS";
        //Inner Panel (Container, Blue, Draggable, inside Outer Panel)
        Panel eb = new Panel();
        eb.ID = "CourseBoxe" + electiveID + "$" + selectedCourseID;
        eb.CssClass = "courseLabelCSS";
        //Elective Name Text (inside Inner Panel)
        Literal lit = new Literal();
        lit.Text = "<span style=\"font-size:12px;\">Elective: " + electiveName + " (" + credits + ")" + "</span><br />";
        //Elective Choices Dropdown (inside Outer Panel)
        DropDownList db = new DropDownList();
        db.ID = electiveID + "%" + term + "%" + selectedCourseID;
        db.Width = new Unit("90%");
        db.AutoPostBack = true;
        db.SelectedIndexChanged += new EventHandler(chooseElectiveOption);
        db.Items.Add(new ListItem("Choose Option", "" + -1));
        String selectedName = "";
        foreach (String i in choiceList.Keys)
        {
            Course c = choiceList[i];
            String name = c.getDpt() + c.getNum() + ": " + c.getName();
            db.Items.Add(new ListItem(name, "" + i));
            if (selectedCourseID == i)
            {
                selectedName = name;
            }
        }
        //Selected Course Name Text (inside Inner Panel)
        lit.Text += "<span>" + selectedName + "</span>";
        //Elective Info Button (inside Outer Panel)
        Button bb1 = new Button();
        bb1.Text = "Manage";
        bb1.ID = "mne" + selectedCourseID + "%" + electiveID;
        bb1.CssClass = "courseButtonCSS";
        bb1.Click += new EventHandler(ManageCourseButtonGV_Click);
        Button bb2 = new Button();
        bb2.Text = "Remove";
        bb2.ID = "rme%" + selectedCourseID + "%" + electiveID;
        bb2.CssClass = "courseButtonCSS";
        bb2.OnClientClick = "javascript:return confirm('Are you sure you want to remove this elective?');";
        bb2.Click += new EventHandler(RemoveCourseButtonGV_Click);
        //Add controls to Inner Panel
        eb.Controls.Add(lit);
        //Add controls to Outer Panel
        p.Controls.Add(eb);
        p.Controls.Add(db);
        p.Controls.Add(new LiteralControl("<br /><center>"));
        p.Controls.Add(bb1);
        p.Controls.Add(new LiteralControl("&nbsp;"));
        p.Controls.Add(bb2);
        p.Controls.Add(new LiteralControl("</center>"));

        //Add elective to correct semester region
        switch (regionNumber)
        {
            case 1:
                SemesterRegion1.Controls.Add(p);
                SemesterRegion1.Controls.Add(new LiteralControl("<br />"));
                break;
            case 2:
                SemesterRegion2.Controls.Add(p);
                SemesterRegion2.Controls.Add(new LiteralControl("<br />"));
                break;
            case 3:
                SemesterRegion3.Controls.Add(p);
                SemesterRegion3.Controls.Add(new LiteralControl("<br />"));
                break;
            case 4:
                SemesterRegion4.Controls.Add(p);
                SemesterRegion4.Controls.Add(new LiteralControl("<br />"));
                break;
            case 5:
            default:
                SemesterRegion5.Controls.Add(p);
                SemesterRegion5.Controls.Add(new LiteralControl("<br />"));
                break;
        }

        //Dynamic JavaScript - create code for drag source
        JavaScriptPageLoad.Text += "var sourceE" + electiveID + selectedCourseID + " = new AdviseUP.UI.CourseBox($get('MainBox_CourseBoxe" + electiveID + "$" + selectedCourseID + "'), 'e" + electiveID + "s" + selectedCourseID + "'); ";
        JavaScriptPageLoad.Text += "sourceE" + electiveID + selectedCourseID + ".initialize();";
    } //end createElectiveBox()

    /// <summary>
    /// UpdateSemesterCreditsLabel()
    /// Graphical View Function
    /// 
    /// Updates the label listing how many credits being taken in a semester.
    /// </summary>
    /// <param name="sem">int sem - the semester to update</param>
    /// <param name="credits">int creditsToAdd - the number of credits to add to the running total</param>
    private void UpdateSemesterCreditsLabel(int sem, double creditsToAdd)
    {
        int space = 0;
        double creditsSoFar = 0;
        switch (sem)
        {
            case 1:
                space = SemesterCreditsLabel1.Text.IndexOf(' ');
                creditsSoFar = Convert.ToDouble(SemesterCreditsLabel1.Text.Substring(space + 1));
                creditsSoFar += creditsToAdd;
                SemesterCreditsLabel1.Text = "Credits: " + creditsSoFar;
                break;
            case 2:
                space = SemesterCreditsLabel2.Text.IndexOf(' ');
                creditsSoFar = Convert.ToDouble(SemesterCreditsLabel2.Text.Substring(space + 1));
                creditsSoFar += creditsToAdd;
                SemesterCreditsLabel2.Text = "Credits: " + creditsSoFar;
                break;
            case 3:
                space = SemesterCreditsLabel3.Text.IndexOf(' ');
                creditsSoFar = Convert.ToDouble(SemesterCreditsLabel3.Text.Substring(space + 1));
                creditsSoFar += creditsToAdd;
                SemesterCreditsLabel3.Text = "Credits: " + creditsSoFar;
                break;
            case 4:
                space = SemesterCreditsLabel4.Text.IndexOf(' ');
                creditsSoFar = Convert.ToDouble(SemesterCreditsLabel4.Text.Substring(space + 1));
                creditsSoFar += creditsToAdd;
                SemesterCreditsLabel4.Text = "Credits: " + creditsSoFar;
                break;
            case 5:
            default:
                space = SemesterCreditsLabel5.Text.IndexOf(' ');
                creditsSoFar = Convert.ToDouble(SemesterCreditsLabel5.Text.Substring(space + 1));
                creditsSoFar += creditsToAdd;
                SemesterCreditsLabel5.Text = "Credits: " + creditsSoFar;
                break;
        }
    } //end UpdateSemesterCreditsLabel()

    /// <summary>
    /// searchForCourseToModify()
    /// List View Function
    /// 
    /// Moves a course or elective in list view
    /// </summary>
    private void searchForCourseToModify()
    {
        //Find the course/elective
        List<Course> courses = populateCourses();
        List<Elective> electives = populateElectives();

        String startYear = SharedFunctions.getAdviseeStartYear(Session["Advisee_adviseeID"].ToString());
        String startSemester = SharedFunctions.getAdviseeStartSemester(Session["Advisee_adviseeID"].ToString());

        String termCode = "ERROR";
        if(MoveYearList.SelectedItem.Text.Equals("Transfer Credits"))
        {
            if(startSemester.Equals("Fall"))
            {
                termCode = SharedFunctions.convertToTermCode(startYear, "Summer");
            }
            else if (startSemester.Equals("Summer"))
            {
                termCode = SharedFunctions.convertToTermCode(startYear, "Spring");
            }
            else
            {
                String moveYear = (Convert.ToInt32(startYear) - 1).ToString();
                termCode = SharedFunctions.convertToTermCode(moveYear, "Fall");
            }
        }
        else
            termCode = SharedFunctions.convertToTermCode(MoveYearList.SelectedItem.Text, MoveCourseList.SelectedItem.Text);
        if (ListViewSelectedCourse.Text.Substring(0, 1).Equals("c"))
        {
            String courseID = ListViewSelectedCourse.Text.Substring(1);
            foreach (Course c in courses)
            {
                if (c.getCourseID() == courseID)
                {
                    if (StoredProcedures.updateCourseInSchedule(AdviseeList.SelectedValue, courseID.ToString(), termCode) == StoredProcedures.FAILURE)
                    {
                        //error condition
                    }
                    return;
                }
            }
        }
        else
        {
            //split the text into the electiveID and selectedCourseID 
            String electiveAndCourseID = ListViewSelectedCourse.Text;
            int sloc = electiveAndCourseID.IndexOf("%");
            String selectedCourseID = electiveAndCourseID.Substring(sloc + 1);
            int electiveID = Convert.ToInt32(electiveAndCourseID.Substring(1, sloc - 1));
            foreach (Elective e in electives)
            {
                if (e.getElectiveID() == electiveID && e.getSelectedCourseID() == selectedCourseID)
                {
                    if (StoredProcedures.updateElectiveTermInSchedule(AdviseeList.SelectedValue,
                        e.getElectiveID().ToString(), e.getSelectedCourseID().ToString(), termCode) == StoredProcedures.FAILURE)
                    {
                        //error condition
                    }
                    return;
                }
            }
        }
    } // end searchForCourseToModify()

    /// <summary>
    /// searchForCourseToRemove()
    /// List View Function
    /// 
    /// Deletes a course or elective in list view
    /// </summary>
    private void searchForCourseToRemove()
    {
        //Find the course/elective
        List<Course> courses = populateCourses();
        List<Elective> electives = populateElectives();
        if (ListViewSelectedCourse.Text.Substring(0, 1).Equals("c"))
        {
            String courseID = ListViewSelectedCourse.Text.Substring(1);
            foreach (Course c in courses)
            {
                if (c.getCourseID() == courseID)
                {
                    if (StoredProcedures.removeCourseFromSchedule(AdviseeList.SelectedValue, courseID.ToString()) == StoredProcedures.FAILURE)
                    {
                        //error condition
                    }
                    return;
                }
            }
        }
        else
        {
            String electiveAndCourseID = ListViewSelectedCourse.Text;
            int sloc = electiveAndCourseID.IndexOf("%");
            String selectedCourseID = electiveAndCourseID.Substring(sloc + 1);
            int electiveID = Convert.ToInt32(electiveAndCourseID.Substring(1, sloc - 1));
            foreach (Elective e in electives)
            {
                if (e.getElectiveID() == electiveID && e.getSelectedCourseID() == selectedCourseID)
                {
                    if (StoredProcedures.removeElectiveFromSchedule(AdviseeList.SelectedValue, e.getElectiveID().ToString(), e.getSelectedCourseID().ToString()) == StoredProcedures.FAILURE)
                    {
                        //error condition
                    }
                    return;
                }
            }
        }
    } // end searchForCourseToRemove()

    /// <summary>
    /// ChangeDisplayedSemesterHelper()
    /// List View Function
    /// 
    /// Displays the appropriate semesters depending on the advisee's start year
    /// </summary>
    /// <param name="MoveYearList">The move year list to manipulate</param>
    /// <param name="MoveSemesterList">The move semester list to manipulate</param>
    private void ChangeDisplayedSemesterHelper(DropDownList MoveYearList, DropDownList MoveSemesterList)
    {
        if (MoveYearList.SelectedItem == null)
            return;
        int intStartYear = Convert.ToInt32(SharedFunctions.getAdviseeStartYear(AdviseeList.SelectedValue));
        String startSemester = SharedFunctions.getAdviseeStartSemester(AdviseeList.SelectedValue);
        int moveYear = 0;
        if (MoveYearList.SelectedItem.Text.Equals("Transfer Credits"))
        {
            if (startSemester.Equals("Spring"))
                moveYear = intStartYear - 1;
            else
                moveYear = intStartYear;
            MoveSemesterList.Items.Clear();
            MoveSemesterList.Items.Add(new System.Web.UI.WebControls.ListItem("----"));
            return;
        }
        else
            moveYear = Convert.ToInt32(MoveYearList.SelectedItem.Text);
        int selectedSemesterIndex = MoveSemesterList.SelectedIndex;
        MoveSemesterList.Items.Clear();
        if (moveYear == intStartYear)
        {
            if (startSemester.Equals("Fall"))
            {
                MoveSemesterList.Items.Add(new ListItem("Fall"));
            }
            else if (startSemester.Equals("Summer"))
            {
                MoveSemesterList.Items.Add(new ListItem("Fall"));
                MoveSemesterList.Items.Add(new ListItem("Summer"));
            }
            else
            {
                MoveSemesterList.Items.Add(new ListItem("Fall"));
                MoveSemesterList.Items.Add(new ListItem("Spring"));
                MoveSemesterList.Items.Add(new ListItem("Summer"));
                MoveSemesterList.SelectedIndex = selectedSemesterIndex;
            }
        }
        else
        {
            MoveSemesterList.Items.Add(new ListItem("Fall"));
            MoveSemesterList.Items.Add(new ListItem("Spring"));
            MoveSemesterList.Items.Add(new ListItem("Summer"));
            MoveSemesterList.SelectedIndex = selectedSemesterIndex;
        }
    } // end ChangeDisplayedSemesterHelper()

    /// <summary>
    /// generateListViewTable()
    /// List View Function
    /// 
    /// Takes the courses and electives in a student's schedule and displays the information
    /// </summary>
    private void generateListViewTable()
    {
        //Clear all currently existing controls so that we don't get multiple tables
        ListViewCourseTable.Controls.Clear();
        List<Course> courses = populateCourses();
        List<Elective> electives = populateElectives();
        List<Course> electivesAndCourses = new List<Course>();
        //If the student is uninitialized, just return out of the function
        String startYear = SharedFunctions.getAdviseeStartYear(AdviseeList.SelectedItem.Value);
        if (startYear.Equals("Uninitialized"))
            return;
        SharedFunctions.displayViolations(ViolationsLabel, (List<String>)SharedFunctions.checkSchedule(AdviseeList.SelectedValue, populateCourses(), populateElectives())["violationMessages"] );
        int intStartYear = Convert.ToInt32(startYear);
        foreach (Course c in courses)
        {
            electivesAndCourses.Add(c);
        }
        foreach (Elective e in electives)
        {
            electivesAndCourses.Add(e);
        }
        int largestStartDate = 0;
        //Determine the earliest date and also the number of years to put in the list view
        foreach (Course c in electivesAndCourses)
        {
            int term = Convert.ToInt32(c.getYear());
            if (term > largestStartDate)
            {
                largestStartDate = term;
            }
        }
        int numberOfYears = (largestStartDate - intStartYear) + 1;
        String startSemester = SharedFunctions.getAdviseeStartSemester(AdviseeList.SelectedValue);
        String starTerm = SharedFunctions.convertToTermCode(startYear, startSemester);
        if (startSemester.Equals("Fall"))
        {
            intStartYear++;
            // if(numberOfYears != 0)
            // numberOfYears--;
        }

        //create Transfer Credits Cell
        TableRow first = new TableRow();
        TableCell transfer = new TableCell();
        transfer.Width = new Unit("33%");
        transfer.CssClass = "listCell";
        transfer.Controls.Add(new LiteralControl("Transfer Credits<br />"));
        double creds = 0;

        foreach (Course course in electivesAndCourses)
        {
            
            //if start semester is Fall
            if (Convert.ToInt32(course.getTerm()) < Convert.ToInt32(starTerm))
            {
                creds += course.getCredits();
                //Create a radio button
                RadioButton radio = new RadioButton();
                if (course is Elective)
                {
                    Elective elective = course as Elective;
                    radio.Text = "Elective: " + course.getDpt() + course.getNum() + " " + course.getName() + " (" + course.getCredits() + ")";
                    radio.ID = "e" + elective.getElectiveID() + "%" + elective.getSelectedCourseID();
                }
                else
                {
                    radio.Text = course.getDpt() + course.getNum() + " " + course.getName() + " (" + course.getCredits() + ")";
                    radio.ID = "c" + course.getCourseID();
                }
                radio.GroupName = "Schedule";
                radio.AutoPostBack = true;
                //Adds an event handling function to be called when the radio button is selected
                radio.CheckedChanged += new EventHandler(getSelectedRadio);
                transfer.Controls.Add(radio);
                transfer.Controls.Add(new LiteralControl("<br />"));
            }
        }
        transfer.Controls.Add(new LiteralControl("Credits: "+creds));
        first.Controls.Add(transfer);
        ListViewCourseTable.Controls.Add(first);

        //Iterate for as many years as was just determined
        for (int i = intStartYear; i < intStartYear + numberOfYears; i++)
        {
            TableRow r = new TableRow();
            //Put all the fall, spring, and summer courses in their place appropriately
            for (int j = 0; j < 3; j++)
            {
                int year = i;
                TableCell c = new TableCell();
                c.Width = new Unit("33%");
                c.CssClass = "listCell";
                String semesterName = "";
                if (j == 0)
                {
                    semesterName = "Fall";
                    year--;
                }
                else if (j == 1)
                {
                    semesterName = "Spring";
                }
                else
                {
                    semesterName = "Summer";
                }
                //Create a new control on the page to add radio buttons to
                c.Controls.Add(new LiteralControl(semesterName + " " + year + "<br />"));

                double credits = 0;
                foreach (Course course in electivesAndCourses)
                {
                    if (!semesterName.Equals("Fall"))
                    {
                        if (course.getYear() == i && course.getSemester().Equals(semesterName))
                        {
                            credits += course.getCredits();
                            //Create a radio button
                            RadioButton rb = new RadioButton();
                            if (course is Elective)
                            {
                                Elective elective = course as Elective;
                                rb.Text = "Elective: " + course.getDpt() + course.getNum() + " " + course.getName() + " (" + course.getCredits() + ")";
                                rb.ID = "e" + elective.getElectiveID() + "%" + elective.getSelectedCourseID();
                            }
                            else
                            {
                                rb.Text = course.getDpt() + course.getNum() + " " + course.getName() + " (" + course.getCredits() + ")";
                                rb.ID = "c" + course.getCourseID();
                            }
                            rb.GroupName = "Schedule";
                            rb.AutoPostBack = true;
                            //Adds an event handling function to be called when the radio button is selected
                            rb.CheckedChanged += new EventHandler(getSelectedRadio);
                            c.Controls.Add(rb);
                            c.Controls.Add(new LiteralControl("<br />"));
                        }
                    }
                    else
                    {
                        if (course.getYear() == i - 1 && course.getSemester().Equals(semesterName))
                        {
                            credits += course.getCredits();
                            //Create a radio button
                            RadioButton rb = new RadioButton();
                            if (course is Elective)
                            {
                                Elective elective = course as Elective;
                                rb.Text = "Elective: " + course.getDpt() + course.getNum() + " " + course.getName() + " (" + course.getCredits() + ")";
                                rb.ID = "e" + elective.getElectiveID() + "%" + elective.getSelectedCourseID();
                            }
                            else
                            {
                                rb.Text = course.getDpt() + course.getNum() + " " + course.getName() + " (" + course.getCredits() + ")";
                                rb.ID = "c" + course.getCourseID();
                            }
                            rb.GroupName = "Schedule";
                            rb.AutoPostBack = true;
                            //Adds an event handling function to be called when the radio button is selected
                            rb.CheckedChanged += new EventHandler(getSelectedRadio);
                            c.Controls.Add(rb);
                            c.Controls.Add(new LiteralControl("<br />"));
                        }
                    }
                }
                c.Controls.Add(new LiteralControl("Credits: " + credits));
                r.Controls.Add(c);
            }
            ListViewCourseTable.Controls.Add(r);
        }
    } // end generateListViewTable()
	
	// setEverything
	//
	// A helper method that sets the boolean values for several functions
	//
	// @param uninitView the bool for setUnitializedView
	// @param addCourse the bool for setAddCourseView
	// @param addElec the bool for setAddElectiveView
	// @param notes1 the first bool for setNotesView
	// @param notes2 the second bool for setNotesView
	// @param graphic the bool for setGraphicView
	// @param list the bool for setListView
	// @param page1 the first bool for setPageControls
	// @param page2 the second bool for setPageControls
	// @param page3 the third bool for setPageControls
	// @param page4 the fourth bool for setPageControls
    // @param craete the bool for createElectiveView
	private void setEverything(bool uninitView, bool addCourse, bool addElec, bool notes1, bool graphic, bool list, bool page1, bool page2, bool page3, bool page4, bool create){
		setUninitializedView(uninitView);
        setAddCourseView(addCourse);
        setAddElectiveView(addElec);
		setNotesView(notes1);
        setGraphicalView(graphic);
        setListView(list);
        setPageControls(page1, page2, page3, page4);
		
		//Functions being added
        setCreateElectiveView(create);
	}

    protected void AddSelectedElectiveButton_Click(object sender, EventArgs e)
    {
        return;
    }
}
